2017-08-04 70 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); 
}