How to unsubscribe from ngrx/store?

自闭症网瘾萝莉.ら 提交于 2019-12-18 19:30:13

问题


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

回答1:


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



回答2:


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



回答3:


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.




回答4:


You don't need to subscribe in first place use | async in your template. Everything you get from store is observable, let angular handle your subscription. Here is api



来源:https://stackoverflow.com/questions/47496383/how-to-unsubscribe-from-ngrx-store

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!