从ZoneAvarePromise Angular2可以观察到

Velidan

我试图提出请求链,通过数据填充结果arr并进行解析。在有承诺的情况下,这是正常的,但是Angular 2将RxJ与其订户一起使用。

所以我努力做到这一点

 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,它在value字段中包含另一个非常奇怪的对象:ZoneAwarePromise,并且在我的结果中存在该对象__zone_symbol__value。

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

谢谢你的帮助。

蒂埃里圣堂武士

这是因为您在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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章