Last active
December 28, 2020 08:39
-
-
Save samteb/52ca775a325a78edc89e5a77f3beb29f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum ListLevel { | |
AUTHORS = 'AUTHORS', | |
ARTICLES = 'ARTICLES' | |
} | |
interface Pagination { | |
first: number; | |
last: number; | |
} | |
@Component({ | |
selector: 'list', | |
templateUrl: 'list.component.html', | |
providers: [ApiService, StoreService] | |
}) | |
export class ListComponent implements OnInit { | |
public showNbOfArticlesDropdown$: Observable<boolean>; | |
public mainList$: Observable<Authors[] | Articles[]>; | |
public listLevel$: Observable<ListLevel>; | |
public pagination$: Observable<Pagination>; | |
public topic$: Observable<string>; | |
public nbArticles$: Observable<number>; | |
constructor( | |
private apiService: ApiService, | |
private storeService: StoreService | |
) { | |
this.listLevel$ = this.storeService.select('listLevel'); | |
this.pagination$ = this.storeService.select('pagination'); | |
this.topic$ = this.storeService.select('topic'); | |
this.nbArticles$ = this.storeService.select('nbOfArticles'); | |
} | |
ngOnInit(): void { | |
this.mainList$ = this.getMainList(); | |
this.showNbOfArticlesDropdown$ = this.showNbOfArticles(); | |
} | |
private getMainList(): Observable<Authors[] | Articles[]> { | |
return combineLatest( | |
this.listLevel$, | |
this.pagination$, | |
this.topic$, | |
).pipe( | |
switchMap(([listLevel, pagination, topic]) => { | |
const { first, last } = pagination; | |
switch (listLevel) { | |
case ListLevel.AUTHORS: | |
return this.nbArticles$.pipe( | |
switchMap(nbArticles => { | |
return this.apiService.fecthAuthors({first, last, topic, nbArticles}) | |
}) | |
); | |
case ListLevel.ARTICLES: | |
return this.apiService.fecthArticles({ first, last, topic }); | |
default: | |
break; | |
} | |
}) | |
) | |
} | |
private getArticlesByAuthor(authorId: number): Observable<Articles[]> { | |
return this.apiService.fetchArticlesByAuthor(authorId); | |
} | |
private showNbOfArticles(): Observable<boolean> { | |
return this.listLevel$.pipe( | |
map(listLevel => { | |
switch (listLevel) { | |
case ListLevel.AUTHORS: | |
return true; | |
case ListLevel.ARTICLES: | |
return false; | |
default: | |
break; | |
} | |
}) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment