我正在使用 Angular、ngrx/store 和 rxjs
所以我有一个购物车 reducer 和一个元素 reducer 。
当我从 API 获取商品时,我需要知道它们是否已在购物车中。
因此,由于我已经实现了分页,所以我认为最好的方法是在获取项目的实际服务中进行检查并在 Items 对象内创建 InCart 字段。
我不想在订阅中执行此操作,因为当我获取项目时,我不会更改购物车状态,因此永远不会调用订阅。如果我使用 map 我也无法访问服务中的数据。
所以我真的不确定如何以“最佳实践方式”做到这一点。
也许我也可以以老式方式将 Cart 对象保存在 Cart 服务中,但我认为这不是最佳实践。
下面的代码对我来说是理想的情况。 (但是 ofc 这不起作用,因为我无法使用 pluck 或 map 访问购物车对象。)
getItems(): Observable<Item[]> {
return this.http.get(url)
.map(this.extractData)
.map(this.extractItemlist)
.catch(this.handleError)
}
private extractItemlist(res: ApiResponse) {
switch (res.response.type) {
case ApiResponse.TYPE.ERROR:
throw res.response.data.message
case ApiResponse.TYPE.SUCCESS:
this.checkIfItemsAreInCart(res.response.data.list)
return res.response.data.list
}
}
private checkIfItemsAreInCart(items: Item[]) {
const cart = this.store.select<CartState>('cart').pluck('cart')
for (const item of items) {
for (const cartItem of cart.items) {
if (item.details.item_id === +cartItem.item_id) {
item.inCart = true
} else {
item.inCart = false
}
}
}
}
有人知道如何实现这一目标吗?我对可观察的东西很陌生,所以可能这就是为什么我仍然没有想出一个好的解决方案。
我真的很感激一些帮助。
最佳答案
I do not want to do it in subscribe because when I'm fetching Items I'm not changing the Cart state so the subscribe will never be called
Observable 的订阅将在您第一次调用时被调用,因此不需要“更改”。
private checkIfItemsAreInCart(items: Item[]) {
this.store.select<CartState>('cart')
.take(1)
.subscribe(cart => {
for (const item of items) {
for (const cartItem of cart.items) {
if (item.details.item_id === +cartItem.item_id) {
item.inCart = true
} else {
item.inCart = false
}
}
}
});
}
关于javascript - 即时访问可观察数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44579281/