订阅后对象中的数组未定义

时间:2017-09-25 09:51:43

标签: javascript angular typescript asynchronous subscribe

我试图在多次http请求之后获取一个元素但是有一个我无法解决的异步问题。发布我的代码:

在我的服务中获取功能:

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?

1 个答案:

答案 0 :(得分:0)

您要将Observablehttp.get()转换为Promise,但您永远不会对Promise做任何事情。因此,虽然stations已定义在您所说的位置,但Promise尚未完成,因此currentListing属性将不定义。

使用Observable或Promise时,您必须始终等待结果。所以在这种情况下,如果你想使用promises,你需要将它们全部收集在一起,而不是输出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)');
    });
});
相关问题