Kim*_*ino 7 observable rxjs typescript angular2-observables angular
我正在编写一个Angular 4应用程序HttpClient
,用于显示电影放映时间.数据所在的有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
}
}]
Run Code Online (Sandbox Code Playgroud)
我有服务可以检索title
和name
剧院.但是现在我必须使用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
吗?
我已经包含了一个我正在尝试构建的示例
通常,当你有一个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)
归档时间: |
|
查看次数: |
6577 次 |
最近记录: |