2017-03-01 47 views
2

我有一個小問題,合併兩個數據源到一個界面Angular2 /打字稿「地圖」兩個觀測量到一個接口

有一個接口

export interface IProvince { 
    code: number; 
    name: string; 
    svgData: string; 
    part: number; 
    color: string; 
} 

現在我有兩個不同的數據源,其中一個爲我提供了以下字段的數據:[code,name,svgData,part][color]來自另一個可觀察的數據。

getAllProvince(): Observable<IProvince[]> 
    { 
    return <Observable<IProvince[]>>this.http 
     .get('url') 
     .map((response: Response) => <IProvince[]>response. 
     .catch(this.handleError) 
     .finally(() => { 
     this.loader.complete(); 
     console.log("Data: ", this.provinceData); 
     }); 

    } 
    getLegendData(): Observable<ILegend[]> { 
    return Observable.of(this.legendData); 
    } 

    getStyleColorData(part: number) { 
    let color: ILegend; 
    return this.getLegendData().subscribe((items: ILegend[]) => color = items.find(p => p.part == part)); 
    } 

問題是,目前我缺乏數據[顏色],我不知道如何「即時」添加另一個函數的值。

這裏我有函數:getStyleColorData(part:number)應該給我「顏色」後,我[部分]從[getAllProvince()]。 問:有兩種方法可以將這兩種方法結合起來,或者我可能會走錯方向?

的Tx的答案和解決方案:)

+0

什麼是this.legendData?一個簡單的數組?如何從ILegend獲取一個顏色字符串? – magnattic

+0

現在是Array,但應該是來自服務器的另一個數據。例如:{ 部分:1, 名: 「Quantyl 1」, 顏色: 「#B4572C」 }, –

回答

0

如果有兩個觀測量(例如,從http請求,你可以用Observable.combineLatestObservable.withLatestFrom結合他們

嘗試是這樣的:

getProvinces() { 
    return this.http 
    .get('url') 
    .map(response => response.json() as IProvince[]) 
    .withLatestFrom(this.getLegendData(), (provinces, legendData) => ({provinces, legendData}) 
    .map(combined => combined.provinces.map(
      province => province.color = combined.legendData.find(legend => legend.part == province.part).color)); 
} 

getLegendData() { 
    return this.http 
    .get('url2') 
    .map(response => response.json() as ILegend[]); 
} 
+0

我試試這個,但是當做某事喜歡thah:L combineMapdata(){ Observable.combineLatest(this.getAllProvince(),this.getLegendData ())。subscribe((data:any []):void => {console.log(data); //盒 - 數據[0] //玻璃 - 數據[1] }); } } ii得到了「控制檯/服務器垃圾郵件,請求每一秒鐘,我相信它與某人observables –

+0

我添加了一個例子,你可以嘗試如果問題仍然存在,當你嘗試這樣? – magnattic

+0

現在是:(Property'color '類型'IProvince'上不存在)。我相信當我做「第一次映射我的顏色停止存在於上下文中, –