我编写了如下代码
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对象。第二个对象应该传递数组中的每个对象并进行更新。但是整个对象被传递给第二个map方法而不是每个单独的对象。看起来我的理解是错误的。
答案 0 :(得分: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);
}