3

I have an angular 2 project, in which I have a couple of components. One of the components keeps track of a member (that is the aforementioned BehaviorSubject) using a subscription.

The BehaviorSubject's value is updated and pushed when a user clicks a button.

However, when subscribing, the only value ever pushed is the original value (that is 0).

The Navbar component is the subscriber, where in CountService the BehaviorSubject is declared.

My CountService:

@Injectable()
export class CountService {
    private count:number;
    public countObservable:BehaviorSubject<number>;
    public savedItems = { campaigns: [], news: [] };

    constructor (private http: Http) {
        this.count=0;
        this.countObservable = new BehaviorSubject<number>(this.count);
        this.countObservable.next(this.count);
    }

    keep(keepId: string, type: string){
        !!this.savedItems[type].length ?
            this.savedItems[type].find(i => i == keepId).length ?
            console.log('exist') : this.keepInSavedItems(keepId, type)
            this.keepInSavedItems(keepId, type);
    }

    keepInSavedItems(keepId, type){
        this.savedItems[type].push(keepId);
        this.count++;
        this.countObservable.next(this.count);
    }
}

My Navbar Component:

@Component({
  selector: 'navbar',
  templateUrl: './navbar.component.html',
  providers: [ CountService ]
})
export class NavigationbarComponent implements OnInit {
  count:number;

  constructor(public countService: CountService){
    this.count=0;
  }

  ngOnInit() : void {
    this.countService.countObservable.subscribe( count => this.count=count);
  }
}
Dan Bachar
  • 149
  • 2
  • 12

2 Answers2

4

You will get a new instance of CountService for every NavigationbarComponent when you provide the service in the component. If the component is added by the router, each route change might destroy and recreate the component and the service.

If you instead provide the service only in @NgModule() (only non-lazy-loaded modules), then there will only be one single instance for your whole application.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
4

Probably, that is happening because of providers array used in individual components.

remove provides:[CountService] from individual components and declare it in rootcomponent's @NgModule

micronyks
  • 54,797
  • 15
  • 112
  • 146