I trying to make chain of request, fill result arr by data and parse it. In case with promises it's normal, but Angular 2 use RxJs with theirs subscribers etc.
So I try to make this
private getPatientPrefPharmacies(patientId: string): Observable {
return this._http.get(this._config.getPatientFeauturesJsonUrl(patientId, this.preferredPharmaciesPropName))
.map(res => {
return Observable.of(this.getAggregatedPatientPrefPharmData(res.json()) );
})
.catch(this.handleError)
}
private getAggregatedPatientPrefPharmData (patientPrefPharmList: Object[]) {
let chain: Promise = Promise.resolve(),
results = [];
patientPrefPharmList.forEach((patPharm) => {
chain = chain
.then(() => {
return new Promise((res, rej) => {
this.getPharmacyDetail(patPharm.pharmacyId)
.subscribe(
pharmData => {
if (pharmData.result.pharmacy[0]) {
patPharm.pharmData = pharmData.result.pharmacy[0];
res(patPharm)
}
},
err => rej(err)
)
});
})
.then(result => {
results.push(result);
})
});
return chain.then(() => {
return results
})
}
And subscribe for it
this._prefPharmSrvc.getPatientPrefPharmacies(this.patientId)
.subscribe(
prefPharmList => this.patientPrefPharmList = prefPharmList,
err => console.log(err)
);
But I got strange object: ScalarObservable that contains in value field another very strange object: ZoneAwarePromise and in this object exist property __zone_symbol__value with my results.
I can parse data from this, but I don't sure that is correct. Maybe I did something wrong and much better way exist?
Thanks for any help.
It's because you return an observable within the callback of the map operator:
return this._http.get(this._config.getPatientFeauturesJsonUrl(patientId, this.preferredPharmaciesPropName))
.map(res => {
return Observable.of(this.getAggregatedPatientPrefPharmData(res.json()) ); // <---
})
.catch(this.handleError)
Either you return a raw value (not an observable) in the map operator callback either you use the flatMap operator if you need an observable.
Here is the way I would refactor your code:
private getPatientPrefPharmacies(patientId: string): Observable {
return this._http.get(this._config.getPatientFeauturesJsonUrl(patientId, this.preferredPharmaciesPropName))
.flatMap(res => {
return Observable.fromPromise(this.getAggregatedPatientPrefPharmData(res.json()));
})
.catch(this.handleError);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With