从ZoneAvarePromise Angular2可观察到

时间:2016-06-07 09:45:56

标签: angular

我试图建立请求链,用数据填充结果并解析它。 如果是承诺,这是正常的,但Angular 2使用RxJs与他们的订户等。

所以我试着做这个

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

订阅它

 this._prefPharmSrvc.getPatientPrefPharmacies(this.patientId)
            .subscribe(
                prefPharmList => this.patientPrefPharmList = prefPharmList,
                err => console.log(err)
            );

但我有一个奇怪的对象: ScalarObservable ,它在值字段中包含另一个非常奇怪的对象: ZoneAwarePromise ,在这个对象中存在属性__zone_symbol__value和我的结果。

我可以从中解析数据,但我不确定这是否正确。也许我做错了什么,存在更好的方式?

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

这是因为您在map运算符的回调中返回了一个observable:

return this._http.get(this._config.getPatientFeauturesJsonUrl(patientId, this.preferredPharmaciesPropName))
    .map(res => {
       return Observable.of(this.getAggregatedPatientPrefPharmData(res.json()) ); // <---
    })
    .catch(this.handleError)

要么在map运算符回调中返回原始值(不是可观察的),要么使用flatMap运算符,如果需要可观察的话。

以下是重构代码的方法:

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);
}
相关问题