使用 Angular 中另一个的响应调用另一个可观察对象 4

Calling another observable with the response of another in Angular 4

我正在编写一个 Angular 4 应用程序,使用 HttpClient 显示电影放映时间。数据所在的文件有2个JSON:showtimes.jsonmovies.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
}
}]

我有服务可以检索剧院的 titlename。但现在我必须使用 showtimes object 中的值来显示正确的标题名称。如您所见,b4c2c326a4d335da654d4fd944bf88d0 是电影标题的 ID,可以从 movies.json 文件中检索。

到目前为止这是我的组件

ngOnInit() {
  this._moviesDataService.getShowtimes()
  .subscribe(res => this.results = res)
}

这是我的服务。

getShowtimes (): Observable<ShowTimes> {
  return this._http.get<ShowTimes>(this._showtimesURL)
}

我的问题是如何使用电影的 ID 检索电影的 title?这需要两个链式 Observable 吗?我需要遍历电影数组并 .filter 它吗?

我提供了一个我正在尝试构建的示例

通常,当你有一个 Observable 并且你需要从 .它和 return 不同的 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)
}

更新

因为您需要两个 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
        }

我认为因为您需要检索所有电影的标题,所以您必须将第一个请求的响应中的 ID 数组链接到一系列电影标题请求中。像这样的东西:(假设你有一个像 getMovieTitle 这样的方法,它根据它的 id 获取电影的数据并且它 returns 一个可观察的)

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*/)

Observable.merge 的作用是什么 Turn multiple observables into a single observable. 所以您将在一次订阅中获得所有结果。

注: 不要忘记将所有这些分配给 subscription 并在组件的 ngOnDestroy 取消订阅(以防止内存泄漏)