【问题标题】:Subscribe stuck in endless loop when state changed状态更改时订阅陷入无限循环
【发布时间】:2018-09-02 01:19:36
【问题描述】:

有人知道如何在商店订阅内向商店发送操作时解决无限循环吗?为了避免循环,我不得不在 store 中添加一个条件,但我想知道是否有更优雅的方式让它工作。

无限循环代码:

ngOnInit(): void {
    this.store.select('admin').subscribe(
      (adminState: AdminState) => {
          const relations = 'dockSubscriptions,dockSubscription.dock,dock.tiles';
          const uri = `users/${adminState.currentUserId}?relations=${relations}`;
          this.apiService.get(uri).subscribe(
            (user: User) => {
              this.store.dispatch(new AppActions.SetCurrentUser(user));
              this.router.navigate(['/']);
              this.currentUserId = adminState.currentUserId;
            },
            (error) => {
              this.auth.logout();
            }
          );
        }
    );
  }

没有循环的代码:

ngOnInit(): void {
    this.store.select('admin').subscribe(
      (adminState: AdminState) => {
        if (adminState.currentUserId && adminState.currentUserId !== this.currentUserId) {
          const relations = 'dockSubscriptions,dockSubscription.dock,dock.tiles';
          const uri = `users/${adminState.currentUserId}?relations=${relations}`;
          this.apiService.get(uri).subscribe(
            (user: User) => {
              this.store.dispatch(new AppActions.SetCurrentUser(user));
              this.router.navigate(['/']);
              this.currentUserId = adminState.currentUserId;
            },
            (error) => {
              this.auth.logout();
            }
          );
        }
      }
    );
  }

有更好的解决方案吗?

【问题讨论】:

  • 据我所知,您的解决方案是解决此问题的最佳方法。

标签: angular observable store infinite-loop ngrx


【解决方案1】:

使用 rxjs 中的 filter 运算符。

this.store.select('admin').pipe(filter(state => { return state.currentUserId && state.currentUserId !== this.currentUserId })).subscribe(...)

或者,您似乎并不需要对用户状态进行公开订阅,因此您可以通过管道发送take(1)

【讨论】:

    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 2013-09-19
    • 2013-03-17
    相关资源
    最近更新 更多