Hi I have an angular 5 application. I have a service method that returns undefined . here is what i am trying to do . i have a function named cloneFlight. i am making a call to flightsService.getCampaignsToClone(this.flight) which is returning value undefined .
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);
});
}
the code for getCampaignsToClone is as follows.
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);
}
in getCampaignsToClone i am making an http call campaignService.getStatuses() that returns Observable . then filtering out some of them and then i make a call to getUnpaginatedCampaigns which is another http call. anyidea what is the best way to write this code so that the method wont return undefined. I think i am probably not utilising the rxjs operators. could someone help me to figure it out .
thank you so much
Rewrite your getCampaignsToClone
method so it returns an Observable sequence. Use flatMap to subscribe to the getUnpaginatedCampaigns observable in turn.
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,
}))
);
}