Typescript方法返回未定义?

时间:2019-04-18 11:27:30

标签: typescript rxjs5 rxjs-pipeable-operators

嗨,我有一个angular 5应用程序。我有一个返回undefined的服务方法。 这就是我想要做的。我有一个名为cloneFlight的函数。我正在打电话给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中,我正在进行http调用campaignService.getStatuses(),该方法返回Observable。然后过滤掉其中一些,然后我打电话给 getUnpaginatedCampaigns,这是另一个http调用。 anyidea编写此代码的最佳方法是什么,以便该方法将不会返回未定义。我想我可能没有利用rxjs运算符。有人能帮我弄清楚吗。

非常感谢

1 个答案:

答案 0 :(得分:1)

重写您的getCampaignsToClone方法,使其返回一个Observable序列。使用flatMap订阅可观察到的getUnpaginatedCampaigns。

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,
    }))
  );
}