我正在使用显示电影放映时间的HttpClient编写Angular 4应用程序.数据所在的位置有2个
JSON文件:showtimes.json和movies.json.
// showtimes.json [{ "id": "2030c64ce72b4e4605cb01f2ba405b7d","name": "Arclight",// need to display this information "showtimes": { "b4c2c326a4d335da654d4fd944bf88d0": [ // need to use this id "11:30 pm","2:45 pm","8:35 pm","4:15 pm","10:30 pm" ] } }] // movies.json [{ "b4c2c326a4d335da654d4fd944bf88d0": { // to retrieve the title,rating,and poster "title": "Fifty Shades Darker",// needs to be displayed "rating": "R",// needs to be displayed "poster": "https://dl.dropBoxusercontent.com/s/dt6wgt92cu9wqcr/fifty_shades_darker.jpg" // needs to be displayed } }]
我有服务可以检索剧院的标题和名称.但是现在我必须使用showtimes对象中的值来显示正确的标题名称.如您所见,b4c2c326a4d335da654d4fd944bf88d0是电影标题的ID,可以从movies.json文件中检索.
到目前为止,这是我的组件
ngOnInit() { this._moviesDataService.getShowtimes() .subscribe(res => this.results = res) }
这是我的服务.
getShowtimes (): Observable<ShowTimes> { return this._http.get<ShowTimes>(this._showtimesURL) }
我的问题是如何使用其ID检索电影的标题?这需要两个链式Observable吗?我需要循环播放电影数组和.filter吗?
我已经包含了一个我正在尝试构建的示例
解决方法
通常,当你有一个Observable时,你需要从中获取东西.它返回一个不同的Observable,你可以使用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
既然你需要两个Observable的结果,你也需要第一个请求第二个的结果,这里有一个想法,你怎么能这样做:
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 }