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

标签 angular typescript rxjs observable angular2-observables

我正在使用显示电影放映时间的 HttpClient 编写 Angular 4 应用程序。数据所在的 JSON 文件有 2 个: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 对象中的值来显示正确的标题名称。如您所见,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 它?

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

最佳答案

通常,当你有一个 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)
}

更新

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

关于angular - 使用 Angular 4 中另一个的响应调用另一个可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48957726/

相关文章:

typescript - Angular2 实现与导入

reactjs - 类型 'value' 上不存在 TypeScript 属性 'HTMLElement'。 react Jest 测试

angular - "async"管道不呈现流更新

css - :first-child with *ngFor is not working properly

angular - 如何在 angular7 中开发在两个不同组件之间切换的选项卡?

angular - Nativescript + Angular ScrollView 滚动到结束监听器

Angular:我将如何链接 Mat-paginator 的 pageSize 来呈现该数量的项目?

javascript - Visual Studio 代码清理任务

typescript - Observable 在 Angular 2 Beta 3 中被破坏了吗?

angular - 在订阅中捕获错误是不可能的吗?