对象内数组订购后未定义
问题描述:
我试图让多个http请求后的元素,但有一个异步问题,我无法解决。发布我的代码:对象内数组订购后未定义
Get函数在我的服务:
get() {
return new Observable(project => {
this.channelsService.get().subscribe(
stations => {
this._stations = stations;
this._stations.forEach((station) => {
station.cssClass = this.channelsService.getCss(station.id.split('/').pop());
station.plstation$thumbnails = this.channelsService.getThumbnails(station.id.split('/').pop());
if (station.plstation$callSign !== '') {
const watchliveUrl = this.watchLiveApi + station.plstation$callSign + '/?schema=1.0.0';
this.http.get(watchliveUrl).subscribe(data => {
const body = data.json();
station.currentListing = body.currentListing;
station.nextListing = body.nextListing;
project.next(stations);
project.complete()
});
}
});
}, (error) => {
this.mapErrorService.mapError(error, 'Listing service (1)');
});
});
}
的get()使用和订阅:
constructor(private listingService: ListingService) {
this.listingService.get().subscribe((stations) => {
this.stripDetails.channelList = stations;
// stations[6].currentListing Not undefined
console.log(stations);
// Now is undefined
console.log(stations[6].currentListing);
}); }
我如何定义站[6] .currentListing ?
答
您正在将Observable
从http.get()
转换为Promise
,但您绝不会对该Promise
做任何事情。因此,虽然stations
被定义在你说的地方,但Promise
不会完成,所以currentListing
属性将是未定义的。
使用Observable或Promise时,您必须始终等待结果。因此,在这种情况下,如果您要使用承诺,则需要将它们汇总在一起,并且不会输出project
,直到它们全部完成。
喜欢的东西:
get() {
return new Observable(project => {
this.channelsService.get().subscribe(
stations => {
this._stations = stations;
let responses = this._stations.map((station) => {
station.cssClass = this.channelsService.getCss(station.id.split('/').pop());
station.plstation$thumbnails = this.channelsService.getThumbnails(station.id.split('/').pop());
if (station.plstation$callSign !== '') {
const watchliveUrl = this.watchLiveApi + station.plstation$callSign + '/?schema=1.0.0';
return this.http.get(watchliveUrl).map(data => {
const body = data.json();
station.currentListing = body.currentListing;
station.nextListing = body.nextListing;
});
}
});
// Wait for all requests to complete.
Rx.Observable.forkJoin(...responses).subscribe(() => {
project.next(stations);
project.complete()
});
}, (error) => {
this.mapErrorService.mapError(error, 'Listing service (1)');
});
});
我与你的意见修改,但它不工作 – goltornate
的问题是你有一个'forEach'循环发射了多个请求,和你调用'project.complete( )当第一个http请求完成时。您必须将所有请求集中在一起,并在完成所有响应后才完成“项目”。你可以使用'Rx.Observable.forkJoin()'。 – Duncan
我要把这个功能准确的放在哪里? – goltornate