代码之家  ›  专栏  ›  技术社区  ›  Hacker

在rxjs中使用map方法更改http返回的数据

  •  1
  • Hacker  · 技术社区  · 7 年前

    我编写了如下代码

    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);
    }
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   CozyAzure    7 年前

    因为您的服务实际上返回了一个数组,所以您应该使用 .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);
    }