Reputation: 197
I have an app in Angular2. Where there is a top-level component containing navigation links, etc.. And the router outlet is nested within this. I'd like an action on one of these nested pages to reflect changes in the top-level coponent.
I've attempted to implement an Observable service in Angular2. And it works within the same component. But when I try to subscribe to the Observable from the root level. I am not getting any events.
My service looks like this:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class Announcer {
// Observable sources
private cartTotalSource = new Subject<number>();
private wishlistTotalSource = new Subject<number>();
// Observable sources
cartTotalAnnounced$ = this.cartTotalSource.asObservable();
wishlistTotalAnnounced$ = this.wishlistTotalSource.asObservable();
// Service message commands
announceCartChange(value: number) {
this.cartTotalSource.next(value);
}
announceWishlistChange(value: number) {
this.wishlistTotalSource.next(value);
}
}
When I use it in the context of a component it works, I can announce, and subscribe to an update within the same file:
ngOnInit(){
this.announcer.cartTotalAnnounced$.subscribe(total => {
this.cartTotal = total;
});
this.announcer.wishlistTotalAnnounced$.subscribe(total => {
this.wishlistTotal = total;
});
}
getCartAndWishlistTotal() {
this.cartService.getCartTotal(CartType.Cart, "")
.subscribe(total => {
this.announcer.announceCartChange(total);
});
this.cartService.getCartTotal(CartType.Wishlist, "")
.subscribe(total => {
this.announcer.announceWishlistChange(total);
});
}
But when, in my top-level component (using the exact same code in ngOnInit() from the above snippet). The subscriber never fires.
Could anyone point me in the direction of what i'm doing wrong?
Upvotes: 1
Views: 262
Reputation: 17944
Check for your Announcer
service provider. Are you providing both in Top level as well as from the component you intend to?
IF yes you might be creating two instances of the service.
You should only provide the Announcer
service in Top level component.
Hope this helps!!
Upvotes: 1