2017-08-04 66 views
1

我寫的代碼像下面更改數據

getCalculatedValuesViaGet = (myData): Observable <RmdResponse> => { 
    return this._http.get('https://jsonplaceholder.typicode.com/posts', 
          { headers: this.getHeaders }) 
     .map((response: Response) => response.json()) 
     .map(x => { x.title = x.title + "hello world" }) 
     .catch(this.handleError); 
} 

基本上我要附加到每個對象一些額外的信息從HTTP方法返回。我的理解是,第一個地圖將其轉換爲JSON對象。第二個對象應該傳遞數組中的每個對象並進行更新。但整個對象傳遞給第二個映射方法而不是每個單獨的對象。看起來我的理解是錯誤的。

回答

2

由於您的服務實際上是返回一個數組,你應該使用.forEach.map變換每個單獨的對象:

getCalculatedValuesViaGet = (myData): Observable<RmdResponse> => { 
    return this._http.get('https://jsonplaceholder.typicode.com/posts', 
     {headers: this.getHeaders}) 
     .map((response: Response) => response.json()) 
     //the following x contains an array of objects, map to transform the data 
     .map(x => { 
       //this map is the function of array, not Observable. 
       //iterate through each object, and update the value of `title` 
       return x.map(y => Object.assign(y, {title: y.title + 'hello world'})) 
      } 
     ) 
     .catch(this.handleError); 
}