Referring to Global Events in Angular 2 I am trying to implement a cart service that emits an event when a new item is added to the cart. I subscribe to this service event in another component called navbar (which is not a child of cart) where I show my number of cart items etc.
My cart service:
export class CartService {
public itemAdded$: EventEmitter<any>;
...
constructor(private http: Http){
this.itemAdded$ = new EventEmitter();
this.cart=[];
}
addToCart(id: any): any {
this.itemAdded$.emit(id);
return this.http.get( this.myUrl + 'add' + '/' + id + '/', { withCredentials:true})
.toPromise()
.then(response => response.json())
}
...
...
}
My navbar component:
@Component({
directives:[ROUTER_DIRECTIVES, Cart],
providers:[CartService],
})
export class Navbar implements OnInit{
...
totalCost: any;
cartItemCount : any;
addedItem: any;
constructor(private cartService: CartService){
this.cartService.itemAdded$.subscribe( (id: any) => {
alert(id);
this.onItemAdded(id);
this.fetchCartElements();
});
}
private onItemAdded(item: any): void {
// do something with added item
this.addedItem = item;
}
...
...
}
However, whenever I add an item, nothing happens in the navbar i.e. alert(id)
or onItemAdded()
are not called automatically so that cartItemCount etc can get automatically updated.
What is going wrong?