angular - NgRx - 在 ngOnInit 中多次分派(dispatch)操作

标签 angular rxjs ngrx

我有一个项目(使用 Angular 和 NgRx),其中有两个页面(两个不同的路由),我需要在用户访问每个页面时获取数据。为实现这一点,有一个组件在初始化时执行以下操作:

code of ngOnInit funcion

retrieveTasks(date) 函数调度导致问题的操作。

当第一次进入该页面时,一切正常,但是当进入另一个页面然后返回该页面时,操作会被分派(dispatch)多次(并且每次您来回访问时都会累加)页)

  • 组件首次初始化时的操作:

first time component is initialized

  • 组件“重新初始化”时的操作:

enter image description here

我是 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/

相关文章:

javascript - 错误引用错误: $ is not defined at angular datatables

angular - 如何修复 Angular 11 'Option "进度”已被弃用?

Angular 2 异步管道不使用 Observable 呈现新值

NGRX 选择器 : factory selector within another selector without prop in createSelector method

heroku - Heroku 上的 Angular CLI 部署

angular - 我可以将 async/await Promises 与可观察的 RXJS 混合使用吗?

reactjs - React、TypeScript 和 RxJS 测试与 Jest 不工作

javascript - 等待两个 observable 完成 zip

angular - Angular 类型的 BehaviorSubject

angular - 非规范化 ngrx store- 设置选择器?