当状态改变时,订阅卡在无限循环中

时间:2018-03-23 11:11:42

标签: angular observable store infinite-loop ngrx

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

无限循环的代码:

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

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

使用rxjs中的$isbn_err="no isbn"; // Check input errors before inserting in database if(empty($isbn_err) ) { // your db code was here 运算符。

filter

或者,您似乎并不需要对用户状态进行开放式订阅,因此您只需管道this.store.select('admin').pipe(filter(state => { return state.currentUserId && state.currentUserId !== this.currentUserId })).subscribe(...)