首页 > 解决方案 > 如果一次失败,为什么角度 ngx 效果不起作用?

问题描述

我使用 Angular 6 和 Ngrx 效果。它的登录效果

@Effect({dispatch: false})
login$ = this.actions$.pipe(
    ofType<Login>(AuthActionTypes.Login),
    tap(action => {
        localStorage.setItem(environment.authTokenKey, action.payload.authToken);
        console.log('login effect');
        this.store.dispatch(new UserRequested());
    }),
);

它发送了用户请求效果

@Effect({dispatch: false})
loadUser$ = this.actions$
.pipe(
    ofType<UserRequested>(AuthActionTypes.UserRequested),
    withLatestFrom(this.store.pipe(select(isUserLoaded))),
    filter(([action, _isUserLoaded]) => !_isUserLoaded),
    mergeMap(([action, _isUserLoaded]) => this.auth.getUserByToken()),
    tap(data => {
        console.log('login effect');
        if (data) {
            this.store.dispatch(new UserLoaded({ user: data['user'] }));
            localStorage.setItem('options', JSON.stringify(data['options']));
            // localStorage.setItem("permissions", data['user'].permissions_list);
            data['user'].permissions_list.forEach((item) => {
                this.permissionsService.addPermission(item.name);
            });
        } else {
            this.store.dispatch(new Logout());
        }
    }, error => {
        this.store.dispatch(new Logout());
    })
  );

如果这个效果被调用并且至少失败一次,它就不会被再次调用。为什么?

标签: angularngrx

解决方案


因为需要控制流。如果您的流有错误,它会按预期停止。

如果您不希望它停止,请考虑将catchError运算符与throwError函数一起使用,或者只是在订阅中捕获错误。

现场观看:

不工作

rxjs.throwError('mocked error')
  .subscribe(
    () => console.log('You should not see this message'),
  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>

在职的

rxjs.throwError('mocked error')
  .subscribe(
    () => console.log('You should not see this message'),
    () => console.log('You should see this message')
  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>

工作国际清算银行

rxjs.throwError('mocked error')
  .pipe(rxjs.operators.catchError(err => rxjs.of('some mocked replacement value')))
  .subscribe(
    () => console.log('You should see this message'),
    () => console.log('You should not see this message')
  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>


推荐阅读