首页 文章

NGRX Effects在错误中破坏app,如何处理错误?

提问于
浏览
0

我在我的应用程序中使用NGRX效果 . 当它失败时,它似乎打破了流 .

@Effect()
createUser$: Observable<Action> = _action$.ofType(fromUser.CREATE_NEW_USER_ACTION)
  .pipe(
    mergeMap((action: fromUser.CreateNewUserAction) =>
      this._tokenService.post('users', action.payload)
        .pipe(
          map(response => {
            this._router.navigate(
              ["dashboard", "users", "view"],
              { queryParams: { id: response.json().message.id } });
            return new fromUser.CreateNewUserCompleteAction(response.json().message);
          },
            catchError(error =>
              of(new fromUser.CreateNewUserFailedAction(error.json().message))
            )
          )
        )
    )
  );

永远不会触发错误操作,我尝试记录 .

1 回答

  • 1

    你的tokenService返回什么?它可能在内部处理来自API调用的任何错误 . 只要您的API调用没有掩盖错误事件,CatchError就应该有效 . 如果是这种情况,您可能需要使用Observable.throw()从该服务中抛出错误 .

    为了便于阅读,我通常将格式更像这样 .

    @Effect() updateUser$: Observable<Action>;
    
    constructor(action$: Actions, tokenService: TokenService) {
    this.updateUser$ = action$.ofType(fromUser.UPDATE_USER_ACTION)
    .pipe(
        mergeMap((action: fromUser.UpdateUserAction) => 
            tokenService.patch(`users/${this.user.id}`, action.payload)
               .pipe(
                  map(response => {
                     this._router.navigate(
                        ["dashboard", "users", "view"], 
                        { queryParams: { id: response.json().message.id } });
                     return new fromUser.UpdateUserCompleteAction(response.json().message); 
                  },
                  catchError(error => 
                     of(new fromUser.UpdateUserFailedAction(error.json().message))
                  )
               )
            )
        )
    );
    }
    

    这段代码看起来应该可行 . 看看你的TokenService .

相关问题