How to unsubscribe from ngrx/store?
When you subscribe you will receive a subscription object on it you can call unsubscribe()
const subscription = this.store.select('somedata').subscribe((state: any) => {
this.somedata = state.data;
});
// later
subscription.unsubscribe();
or
ngOnInit(){
this.someDataSubscription = this.store.select('somedata').subscribe((state: any) => {
this.somedata = state.data;
});
}
ngOnDestroy(){
this.someDataSubscription.unsubscribe();
}
You can get value without directly calling subscribe method, get value by async pipe like
@Component({
template: `
<div>Current Count: {{ counter | async }}</div>
`
})
class MyAppComponent {
counter: Observable<number>;
constructor(private store: Store<AppState>){
this.counter = store.select('counter');
}
}
Here we are using async pipe for getting value. The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
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()})
}