我有这样的可观察结果:
currentPage: 1
items: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
pageSize: 10
totalItems: 6
totalPages: 1
我试图修改items数组中的每个元素,然后返回一个完整的对象。
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)
);
}
但我只得到一个修改过的项目数组,没有currentPage属性、页面大小等。
如何修改项数组并返回整个对象?
您似乎已经熟悉了排列语法(...
(的用法。在将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)
);
}
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)
);
}