2017-09-25 4 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

http.get()Promiseに変換していますが、それ以外のことは絶対に行いません。Promiseしたがって、Promiseは完了していないので、currentListing属性は定義されません。stationsが定義されていますが、

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を呼び出しているです) 'を返します。すべてのリクエストをまとめて、すべてが応答したときにのみ 'project'を完成させる必要があります。このために 'Rx.Observable.forkJoin()'を使うことができます。 – Duncan

+0

どこにこの関数を置くのですか? – goltornate

関連する問題