2017-09-25 54 views
1

我試圖讓多個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 ?

回答

0

您正在將Observablehttp.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)'); 
    }); 
}); 
+0

我與你的意見修改,但它不工作 – goltornate

+0

的問題是你有一個'forEach'循環發射了多個請求,和你調用'project.complete( )當第一個http請求完成時。您必須將所有請求集中在一起,並在完成所有響應後才完成「項目」。你可以使用'Rx.Observable.forkJoin()'。 – Duncan

+0

我要把這個功能準確的放在哪裏? – goltornate