2017-06-01 66 views
0

當我的視圖處於初始化狀態時,發出2個HTTP請求並將數據保存到兩個不同的陣列。我不想在我的html中有兩個for循環來從兩者中獲取信息。我的問題是我怎樣才能將返回的信息推送到一個數組?那可能嗎?我需要使用本地存儲嗎? (接口中的鍵和json響應中返回的鍵名稱完全相同)。將兩個HTTP響應推送到一個數組中

我需要保存ID,組,預置在第一響應和的ColorCode,colorGrade,在的ColorType第二(我已經離開評論在下面的每個訂閱的)

info: infoInterface[]; 
info2: infoInterface[]; 

ngOnInit() { 

    this.getInfo.getPCode() 
    .subscribe(
     (dieInfo: DieInfoInterface[]) => this.dieInfo = dieInfo, 
     // On response I need to store id, group, preset 
     (error: Response) => console.log(error) 
    ); 

    this.getInfo.getCCodes() 
    .subscribe(
     (dieInfo2: DieInfoInterface[]) => { 
     // on response I need to store colorCode, colorGrade, colorType 
     this.dieInfo2 = dieInfo2 

     }, 
     (error: Response) => console.log(error) 
    ); 
} 

的getInfo服務

getPCode(): Observable<any> { 
    return this.http.get('') 
    .map(
     (response: Response) => { 
     return response.json().inform; 
     } 
    ); 
} 

getCCodes(): Observable<any> { 
    return this.http.get('') 
    .map(
     (response: Response) => { 
     return response.json().inform; 
     } 
    ); 
} 

接口

export interface infoInterface { 

    id: number; 
    group: any; 
    colorCode: string; 
    colorGrade: any; 
    colorType: string; 
    preset: string; 
} 

我是如何顯示的數據。目前我正在從info[]顯示的數據,因爲我不想兩個for循環

<div class="row" *ngFor="let i of info"> 
    <div class="info col-sm-3"> 
    <div class="row"> 
     <h1>Die: </h1> 
     <p> {{ info.id }} </p> 
    </div> 

    <div class="row"> 
     <h1>Color Code: </h1> 
     <p> {{ info.group }} </p> 
    </div> 
    </div> 
</div> 
+0

這是不是一個好的做法。單個電話將被觸發相同的請求 – Aravind

+0

你是什麼意思?我應該如何解決它? – ghan

回答

0

結合最新會給你兩個最新項目從您的視頻流,一旦他們都發出。

this.getInfo.getPCode() 
    .combineLatest(this.getInfo.getCCodes()) 
    .subscribe(([pcodes, ccodes]) => { 
    const allcodes = pcodes.map((el, i) => { 
     return { ...el, ...ccodes[i] }; 
    }); 
    }); 
+0

我收到錯誤'錯誤:(38,8)TS2339:屬性'combineLatest'在類型'Observable '上不存在。' – ghan

+0

@ghan您正在使用什麼構建系統(Angular CLI?Webpack?System.js ?)嘗試將'import'rxjs/rx';'添加到文件頂部。 – Harangue

0

以前的答案應該工作,但因爲你得到的是combineLatest不存在的錯誤,我會想象你缺少你import語句

import 'rxjs/add/observable/combineLatest'; 
+0

我剛剛添加了導入,但它仍然不起作用。完整的錯誤是'TS2339:property'combineLatest'在類型'Observable '上不存在'。'我試過將''更改爲'',它仍然不起作用 – ghan

0

的RxJs答案可能是更好,更優雅,但下面也會工作,不需要本地存儲。

info: infoInterface[] = []; 
 

 
ngOnInit() { 
 

 
    this.getInfo.getPCode() 
 
    .subscribe(
 
     (dieInfo: DieInfoInterface[]) => this.info = this.info.concat(dieInfo), 
 
     // On response I need to store id, group, preset 
 
     (error: Response) => console.log(error) 
 
    ); 
 

 
    this.getInfo.getCCodes() 
 
    .subscribe(
 
     (dieInfo2: DieInfoInterface[]) => { 
 
     // on response I need to store colorCode, colorGrade, colorType 
 
     this.info = this.info.concat(dieInfo2) 
 

 
     }, 
 
     (error: Response) => console.log(error) 
 
    ); 
 
}

相關問題