How to unsubscribe from ngrx/store?

Michael Philips picture Michael Philips · Nov 26, 2017 · Viewed 16.9k times · Source

I have a component which gets its data from subscribing to a store.

this.store.select('somedata').subscribe((state: any) => {
  this.somedata = state.data;
});

I want to unsubscribe from this subscription when component is no more, in other places where I am subscribing to some observable, something like this:

this.service.data.subscribe(
   (result: any) => {//data}
);

I unsubscribed it on ngOnOnDestroy, like this:

ngOnDestroy(){
   this.service.data.unsubscribe();
}

But in case of store I'm not able to, it gives me error:

Property 'unsubscribe' does not exist on type 'Store<State>'

Answer

FlavorScape picture FlavorScape · Oct 17, 2018

There's a better way than the top voted answer, a way in which you don't have to manage a bunch of subscriptions, only one. Then you can have as many subscriptions as you want without having to create a bunch of unnecessary vars.

  public ngDestroyed$ = new Subject();

  public ngOnDestroy() {
    this.ngDestroyed$.next();
  }

  public ngOnInit() {
    this.myWhateverObs$
        .pipe(takeUntil(this.ngDestroyed$))
        .subscribe((val)=> { this.whatever()});
    this.myWhateverNPlusOne$
        .pipe(takeUntil(this.ngDestroyed$))
        .subscribe((val)=> { this.whatever()})
  }