Angular:多次订阅ngrx商店火灾

时间:2018-10-01 05:55:54

标签: angular typescript observable ngrx ngrx-store

我有一个带有ngrx商店的应用程序。我正在订阅它,以便通过单击按钮时触发的函数从存储中获取数据,我正在获取所需的数据,但是每次触发该函数时,它似乎都将返回数据的多个副本。再次发射它,它呈指数增长。

所以在我的component.ts中,我有选择器,该选择器已连接到商店以获取数据:

this.data$ = this.store.pipe(select(selectors.dataSelector));

然后单击我的函数(在我的html中)

  onClick() {
     this.data$.subscribe(x =>
       console.log(x)
     );
   }

因此,经过一轮迭代:

enter image description here

两点后:

enter image description here

三点后:

enter image description here

以此类推。有人可以为什么会发生这种情况,或者建议使用其他方法从component.ts中的存储中获取数据?我需要它仅返回一次数据,否则性能会受到很大影响。

谢谢!

1 个答案:

答案 0 :(得分:2)

您每次点击都订阅data$的费用。如果您想这样做,onClick可以在您console.log(x)之后退订或使用rxjs take()

  onClick() {
     this.data$.pipe(take(1)).subscribe(x =>
       console.log(x)
     );
   }

从文档中

为什么要服用

当您仅对第一个设置的发射数量感兴趣时,您想使用take。也许您想查看用户首次进入页面时首次点击的内容,您想要订阅click事件并进行第一次发射。

https://www.learnrxjs.io/operators/filtering/take.html

但是我的建议是您在其他地方订阅商店,例如在组件构造函数中

constructor(store) {
   store.pipe(select(selectors.dataSelector)).subscribe(x => {
       this.componentX = x;
   });
}

然后只需单击即可看到如下数据:

onClick() {
   console.log(this.componentX);
}

这样,您仅在组件初始化时订阅一次。

关于订阅以及如何防止内存泄漏的另一件事是,在组件遭到破坏时始终取消订阅。

https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/

相关问题