2016-06-07 168 views
3

我試圖使請求鏈,數據填充結果ARR和解析它。 如果用承諾這是正常的,但角2與他們的用戶等可觀察ZoneAvarePromise Angular2

使用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_sym bol__value與我的結果。

我可以從這裏解析數據,但我不確定這是否正確。也許我做錯了什麼,更好的方式存在?

感謝您的任何幫助。

回答

3

這是因爲你的map操作的回調中返回一個可觀察到的:在map操作回調

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

要麼你回到原始值(沒有可觀察到的),要麼使用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); 
}