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>'
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()})
}