我正在尝试更新observable subscribe方法中的对象数组。但它并没有像预期的那样更新。 我的实现如下。 Compoent.ts
constructor(private shopHomeService: ShopHomeService) {
this.shopHomeService.shopItemChanged.subscribe(
(item) => {
if (item) {
this.items = shopHomeService.getShopItems();
if (this.items.length > 0) {
const findItem = this.items.find(shopItem => shopItem.Id === item.Id);
if (findItem) {
findItem.OrderQuantity = findItem.OrderQuantity + 1;
} else {
this.items.push(item);
}
} else {
this.items.push(item);
}
this.items = this.items.slice();
shopHomeService.ShopItems = this.items;
this.shopItems = [];
this.shopItems = this.items;
}
}
);
}
Service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class ShopHomeService {
private shopItems = [];
private shopItem: any;
shopItemChanged = new BehaviorSubject<any>(this.shopItem);
constructor() { }
getShopItems() {
console.log(this.shopItems);
return this.shopItems;
}
set ShopItems(shopItems) {
this.shopItems = shopItems;
console.log(this.shopItems);
}
addShopItem(item) {
item.OrderQuantity = 1;
item.Discount = 0;
item.DiscountPercentage = 0;
this.shopItemChanged.next(item);
}
removeShopItem(item) {
this.shopItems = this.shopItems.filter(element => element.Id !== item.Id);
this.shopItemChanged.next(this.shopItems);
}
}
最初 OrderQuantity 属性在数组项的每个对象中设置为1。 当相同类型的对象添加到shopItems时,它将使OrderQuantity的值增加1.逻辑已经实现了上面的代码。但是当商店商品改变时,它总是给出具有 OrderQuantity = 1 的对象数组。 ( shopHomeService.getShopItems()返回OrderQuantity = 1的数组列表,但当 shopHomeService.ShopItems 调用它时发送rderQuantity = 2)