Reputation: 4519
I am trying to return value to this.voucherDetails using subscribe but it doesn't seem to work.
Following is the request to the function getVoucherDetails which has the subscribe function.
voucherIDs: string[];
voucherDetails: Promise<any>[];
this.voucherIDs = ['JV-2005-50','JV-2005-40','JV-2005-30'];
this.voucherDetails = this.voucherIDs
.map(id => this.getVoucherDetails(id));
Promise.all(this.voucherDetails)
.then(() => this.printService.onDataReady());
Following is the function with subscribe to userService which gets data from database.
getVoucherDetails(voucherid) {
var splitvoucher = voucherid.split('-');
var vouchertype = splitvoucher[0];
var vouchermy = splitvoucher[1];
var voucherno = splitvoucher[2];
var vouchernotopass = vouchermy+"-"+voucherno;
var voucherdate;
var enteries;
this.userService.getVoucher(vouchernotopass,vouchertype).subscribe(
res => {
voucherdate = res['voucherdate'];
enteries = res['enteries'];
return { "vouchertype":vouchertype, "vouchernumber": vouchernotopass, "voucherdate": voucherdate, "enteries":enteries};
}
);
}
But it returns undefined. After going through several posts I have come to understand that you can't return from a .subscribe. But I haven't been able to understand a work around on how to resolve this issue.
Upvotes: 0
Views: 1905
Reputation: 3594
You are working asynchronously with Observable, so you need to use callbacks, like with Promise. You should return an Observable (or Promise) in your method and let the caller subscribe to it:
getVoucherDetails(voucherid) {
var splitvoucher = voucherid.split('-');
var vouchertype = splitvoucher[0];
var vouchermy = splitvoucher[1];
var voucherno = splitvoucher[2];
var vouchernotopass = vouchermy+"-"+voucherno;
var voucherdate;
var enteries;
return this.userService.getVoucher(vouchernotopass,vouchertype).pipe(
map(res => {
voucherdate = res['voucherdate'];
enteries = res['enteries'];
return { "vouchertype":vouchertype, "vouchernumber": vouchernotopass, "voucherdate": voucherdate, "enteries":enteries};
})
);
}
Use this method like this:
getVoucherDetails(id).subscribe(v => {
console.log(v.vouchertype);
console.log(v.vouchernumber);
console.log(v.voucherdate);
});
In your case:
forkJoin( // forkJoin waits for Observables to complete and then combine last values they emitted.
this.voucherIDs.map(id => this.getVoucherDetails(id) // array of observable
).subscribe(responses => {
console.log(responses);
this.voucherDetails = responses;
});
Upvotes: 3