Droxx Droxx - 1 year ago 99
TypeScript Question

Angular2 Observable service dosen't seem to be working across components

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';

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) {
announceWishlistChange(value: number) {

When I use it in the context of a component it works, I can announce, and subscribe to an update within the same file:

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.cartService.getCartTotal(CartType.Wishlist, "")
.subscribe(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?

Answer Source

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!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download