如何退订ngrx/store? [英] How to unsubscribe from ngrx/store?

查看:88
本文介绍了如何退订ngrx/store?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,可以通过订阅商店获取其数据.

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

我在ngOnOnDestroy上取消了订阅,就像这样:

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

推荐答案

订阅时,您将收到一个订阅对象,您可以调用unsubscribe()

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

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

ngOnDestroy(){
  this.someDataSubscription.unsubscribe();
}

这篇关于如何退订ngrx/store?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆