У меня проблема с подпиской в Rxjs на Angular. У меня есть компонент A, и от нее я отправляю данные в службу на shopCartChanged = new Subject<ProductModel[]>();
, а мой компонент B подписан на shopCartChanged
. Первый раз не разветвляется, но при отправке второго объекта это работает довольно хорошо, и я получаю все объекты из моей подписки.
Это мой компонент A и метод addToShoppingList
, из которого я отправляю данные:
addToShoppingList(product: ProductModel) {
if (this.shop.setProductCart({...product})){
this.messageService.add('Proizvod je dodat u korpu!!!');
}
}
Мой сервис ShopCartService
и setProductCart
, где я установил дату на Subject
:
setProductCart(product: ProductModel) {
for (let i = 0; i < this.productCart.length; i++) {
if (this.productCart[i].product_id == product.product_id) {
this.productCart[i].numberOfProduct += product.numberOfProduct;
this.shopCartChanged.next(this.productCart);
return true;
}
}
this.productCart.push(product);
this.shopCartChanged.next(this.productCart);
return true;
}
Мой Subject
в моем сервисе ShopCartService
shopCartChanged = new Subject<ProductModel[]>();
Мой компонент B:
ngOnInit () {
this.subscription = this.shopCartService.shopCartChanged.subscribe(
(products: ProductModel[]) => {
this.productCarts = products;
localStorage.setItem('key', JSON.stringify(this.productCarts));
}
);
}