使用 rxjs 修改 observable 中的数组,return 整个对象

Modify array in observable with rxjs, return whole object

我有这样的观察结果:

currentPage: 1
items: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
pageSize: 10
totalItems: 6
totalPages: 1

我试图修改 items 数组中的每个元素,然后 return 整个对象。

   getAllGifts(): Observable<PagedListDTO<GiftIdeaDTO>> {
    return this.http.get<PagedListDTO<GiftIdeaDTO>>(this.urlAPI + '/GiftIdeas/GetAll').
      pipe(
        map(x => x.items.map
          (y => ({ ...y, imageContentB64: y.imageContentB64 + 'Bob' })))
        ,
        tap(console.log)
      );
  }

但我只得到修改后的项目数组,没有当前页面 属性、页面大小等

如何修改项目数组和 return 整个对象?

map(x => 只占 x.items 并且缺少 props 的其余部分。

这应该可以解决问题:

   getAllGifts(): Observable<PagedListDTO<GiftIdeaDTO>> {
    return this.http.get<PagedListDTO<GiftIdeaDTO>>(this.urlAPI + '/GiftIdeas/GetAll').
      pipe(
        map(x => ({...x, items: x.items.map
          (y => ({ ...y, imageContentB64: y.imageContentB64 + 'Bob' })))
        }),
        tap(console.log)
      );
  }

在上面的代码中,x 被映射为包含所有道具,然后 items 使用 x.items.map 更新。

你不会退货,使用这个:

getAllGifts(): Observable<PagedListDTO<GiftIdeaDTO>> {
return this.http.get<PagedListDTO<GiftIdeaDTO>>(this.urlAPI + '/GiftIdeas/GetAll').
    pipe(
        map(x => {
            return {
                ...x,
                items: x.items.map(y => ({ ...y, imageContentB64: y.imageContentB64 + 'Bob' }))
            }
        })
    )
    ,tap(console.log)
    );
}

您似乎已经熟悉spread syntax (...)的用法。您也可以在将 Array#map 应用于 items 属性.

之前将其用于外部对象

尝试以下方法

getAllGifts(): Observable<PagedListDTO<GiftIdeaDTO>> {
  return this.http
    .get<PagedListDTO<GiftIdeaDTO>>(this.urlAPI + '/GiftIdeas/GetAll')
    .pipe(
      map(ideas => ({
        ...ideas,                          // retain properties of the outer object
        items: ideas.items.map(item => ({  // adjust the `items` property
          ...item, 
          imageContentB64: item.imageContentB64 + 'Bob' 
        }))
      })),
      tap(console.log)
    );
}