Calling another observable with the response of another in Angular 4
Usually, when you have one Observable and you need to grab something from . it and return a different Observable, you can use switchMap
:
ngOnInit() { this._moviesDataService.getShowtimes() .switchMap(res => { const id = Object.keys(res[0].showtimes)[0]; // assuming you have one element in your array and you want the first id from showtimes return this.getMovies(id); // assuming, you have a separate method that returns the movies }) .subscribe(res => this.results = res)}
UPDATE
Since you need results of both Observable but also you need the results of the first to request the second here's an idea how you can do this:
ngOnInit() { this._moviesDataService.getShowtimes() .switchMap(res => { const showtimes = res[0].showtimes; const id = Object.keys(showtimes)[0]; return Observable.zip( this.getMovies(id), Observable.of(showtimes[id]) ); }) .subscribe(([movies, showtimes]) => { this.results.movies = movies; // or assign it to some other property this.results.showtimes = showtimes; // and use in the template }
I think because you need to retrieve titles of all the movies, you have to chain the array of IDs in the first request's response, into a series of requests for movies' titles. something like this: (assuming you have a method like getMovieTitle
that gets data of a movie based on it's id and it returns an observable)
this._moviesDataService.getShowtimes() .switchMap(res => { let resArray: any[] = res.map( item=>this._moviesDataService.getMovieTitle( Object.keys(item.showtimes)[0] )) return Observable.merge(...resArray); }) .subscribe(res => /*you will get a new res for each movie title here*/)
what Observable.merge
does, is it Turn multiple observables into a single observable.
so you will get all the results in one subscription.
Note:don't forget to assign all of this to a subscription
and unsubscribe it at ngOnDestroy
of the component (to prevent memory leak)