service.ts
constructor() {
this.cartUpdate = new BehaviorSubject<Array<AppCartItem>>([]);
// this.cartUpdate.subscribe((items) => { // #### 1
// console.log('Service Items : ', items);
// });
}
add(item) : Observable<Array<AppItem>> {
return this.get().pipe(
switchMap(cartItems => {
let index = cartItems.findIndex(i => i.item.id == item.id);
if(index == -1) {
cartItems.push({ item });
}
return this.updateUser({ 'cart': cartItems })
.pipe(
map(() => {
return cartItems;
})
)
}),
catchError(err => {
console.log('Error : ', err);
return throwError(null);
})
).pipe(
map(cartItems => {
this.updateCart(cartItems);
return cartItems;
})
)
}
updateCart(items) {
setTimeout(() => {
this.cartUpdate.next(items); // #### 3
}, 1000);
}
component.ts
ngOnInit() {
this.service.cartUpdate.subscribe((items) => { // ####4
console.log('Items : ', items);
}, (err) => {
console.log('Error : ', err);
});
}
I have provided the code for service and component.
Initially, in the component the subscribe is triggering. No issue in that. #### 4
Now, the add method in service.ts also should trigger the observable after adding the item. #### 3
But the subscribe in component is not triggering for the emit. #### 3
Whereas the subscribe in the constructor for the same Subject is working. #### 1
I am having trouble in figuring out why the subscribe in the component is not working
question from:
https://stackoverflow.com/questions/65903349/subject-next-not-firing-from-inside-observable 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…