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

Kim*_*ino 7 observable rxjs typescript angular2-observables angular

我正在编写一个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
}
}]
Run Code Online (Sandbox Code Playgroud)

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

到目前为止,这是我的组件

ngOnInit() {
  this._moviesDataService.getShowtimes()
  .subscribe(res => this.results = res)
}
Run Code Online (Sandbox Code Playgroud)

这是我的服务.

getShowtimes (): Observable<ShowTimes> {
  return this._http.get<ShowTimes>(this._showtimesURL)
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何title使用其ID 检索电影?这需要两个链式Observable吗?我需要循环播放电影阵列.filter吗?

我已经包含了一个我正在尝试构建的示例 例

Bor*_*nov 9

通常,当你有一个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)
}
Run Code Online (Sandbox Code Playgroud)

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
        }
Run Code Online (Sandbox Code Playgroud)