-5

嗨,我有一个 Angular 5 应用程序。我有一个返回 undefined 的服务方法。这就是我想要做的。我有一个名为 cloneFlight 的函数。我正在调用返回值 undefined 的 flightService.getCampaignsToClone(this.flight) 。

cloneFlight() {
    combineLatest(
      this.translateService.get('CONFIRM.CLONE_FLIGHT', { item: this.flight.name}),
      this.flightsService.getCampaignsToClone(this.flight)
    ).subscribe( ([header, campaigns]) => { 
      this.cloneFlightService.openModal(header,this.flight,campaigns);
    });
  }

getCampaignsToClone 的代码如下。

 getCampaignsToClone(flight: Flight){

    let campaignStatusesIdArr: string[];
    let campaigns: CampaignUnpaginated[] ; 
    this.campaignService.getStatuses().subscribe(
      (data) => { 
        campaignStatusesIdArr = data.filter( x => x.code === (CampaignStatusCode.IN_PROGRESS || 
          CampaignStatusCode.READY)).map( y => y.id);
      }
    );
    let accountId: string = flight.campaign.account.id;    

    this.campaignService.getUnpaginatedCampaigns(
      {
        statuses: campaignStatusesIdArr,
        accounts: accountId
      }
    ).subscribe(data=>{
      console.log(data);
      campaigns = data;
    });
    return Observable.of(campaigns);
  }

在 getCampaignsToClone 中,我正在进行一个返回 Observable 的 http 调用campaignService.getStatuses()。然后过滤掉其中的一些,然后我调用 getUnpaginatedCampaigns 这是另一个 http 调用。知道什么是编写此代码的最佳方法,以便该方法不会返回未定义。我想我可能没有使用 rxjs 运算符。有人可以帮我弄清楚。

太感谢了

4

1 回答 1

1

重写你的getCampaignsToClone方法,让它返回一个 Observable 序列。使用 flatMap 依次订阅 getUnpaginatedCampaigns observable。

getCampaignsToClone(flight: Flight): Observable<CampaignUnpaginated[]> {
 return this.campaignService.getStatuses().pipe(
    map(data => data.filter( x => x.code === (CampaignStatusCode.IN_PROGRESS || CampaignStatusCode.READY)).map(x => x.id)),
    flatMap(ids => this.campaignService.getUnpaginatedCampaigns({
        statuses: ids,
        accounts: flight.campaign.account.id,
    }))
  );
}
于 2019-04-18T11:42:17.583 回答