[英]Modify array in observable with rxjs, return whole object
我有这样的观察:
currentPage: 1
items: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
pageSize: 10
totalItems: 6
totalPages: 1
我正在尝试修改 items 数组中的每个元素,然后返回整个 object。
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 属性、页面大小等。
如何修改项目数组并返回整个 object?
map(x =>
只占x.items
,错过了props
的 rest 。
这应该解决它:
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
被映射为包含所有道具,然后使用x.items.map
更新items
。
您不会退回它们,请使用以下命令:
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)
);
}
您似乎已经熟悉扩展语法 ( ...
)的用法。 在将Array#map
应用于items
属性之前,您还可以将其用于外部 object。
尝试以下
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)
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.