我有一个项目(使用 Angular 和 NgRx),其中有两个页面(两个不同的路由),我需要在用户访问每个页面时获取数据。为实现这一点,有一个组件在初始化时执行以下操作:
retrieveTasks(date)
函数调度导致问题的操作。
当第一次进入该页面时,一切正常,但是当进入另一个页面然后返回该页面时,操作会被分派(dispatch)多次(并且每次您来回访问时都会累加)页)
- 组件首次初始化时的操作:
- 组件“重新初始化”时的操作:
我是 Angular、RxJS 和 NgRx 的新手,想知道我做错了什么以及最好的方法是什么。
最佳答案
问题是你没有取消订阅你的选择(可观察到的),所以即使组件被销毁它们仍然存在
改成这个
export class component implement OnInit, OnDestroy {
private unsubscribeAll: Subject<any> = new Subject<Any>();
ngOnInit() {
this.store.select(selector)
// add takeUntil on all selects or any other observables you subscribe
.pipe(
takeUnitl(this.unsuscribeAll)
)
.subscribe(...) //rest of your code for subscription
}
ngOnDestroy() {
this.unsubscribeAll.next();
this.unsubscribeAll.complete();
}
}
关于angular - NgRx - 在 ngOnInit 中多次分派(dispatch)操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59901167/