I have a scenario where I am fetching a list of items from an Observable in my Angular service. Each item contains an array of subjects, and for each subject, I need to make a separate API call to retrieve its details such as name, description, etc.
Data structure:
- post1
- subjects: ['books', 'cars', 'movies']
While I have the IDs of all the subjects, I require an observable that provides me with all subjects linked to that particular post along with their respective details.
AppService.ts
getPost(id: string): Observable<Post> {
return Observable.of({id: id, subjects: ['books', 'cars', 'movies']});
}
getSubjects(id: string): Observable<Subject[]> {
return this.getPost(id).pipe(
map((post: Post) => post.subjects),
mergeMap((subjects: string[]) => subjects.map((id: string) => this.getSubject(id))),
switchMap(list => list),
);
}
getSubject(id: string): Observable<Subject> {
switch (id) {
case 'books':
return Observable.of({id: 'books', name: 'Books'});
case 'cars':
return Observable.of({id: 'cars', name: 'Cars'});
case 'movies':
return Observable.of({id: 'movies', name: 'Movies'});
}
}
The current implementation returns a stream of objects, but I aim to modify it to return an array containing all subjects.
[DEMO]