【问题标题】:rxjs catchError not working when piped from angular service从角度服务通过管道传输时,rxjs catchError 不起作用
【发布时间】:2018-11-20 21:18:02
【问题描述】:

使用redux和Angular,我有如下效果:

  @Effect()
  public authenticate: Observable<Action> = this.actions
    .ofType(AUTHENTICATE)
    .pipe(
      map((action: AuthenticateAction) => action.payload),
      switchMap(payload => {
        return this.userService.authenticateUser(payload.email, payload.password).pipe(
          map(auth => new AuthenticationSuccessAction({ auth: auth })),
          catchError(error => of(new HttpErrorAction({ error: error })))
        );
      })
    );

服务:

  public authenticateUser(email: string, password: string): Observable<IAuthentication> {
    const formData: FormData = new FormData();
    formData.append('email', email);
    formData.append('password', password);
    return this.httpClient.post('/api/auths/useraccounts', formData) as Observable<IAuthentication>;
  }

当 POST 失败时,永远不会调度 HttpErrorAction。

【问题讨论】:

    标签: angular rest error-handling redux rxjs


    【解决方案1】:

    原来我忘记了我有一个 HttpInterceptor,我发现了这样的 http 错误:

    return next.handle(authReq).pipe(catchError(
          (error) => {
            return of(error);
          }
    

    如果我想将错误冒泡到效果我会做类似的事情:

    return Observable.throw(error);
    

    使用较新版本的 rxjs 更新:

    return throwError(error);
    

    【讨论】:

    • 那么在拦截器开启的情况下,这是否有助于捕捉效果中的错误?
    • @that_guy 你刚刚救了我,一个小时后试图找出为什么错误没有被嵌套的 flatMap 捕获,这就是原因
    • return Observable.throw(error) 对我不起作用,所以我不得不这样做return throwError(error);
    猜你喜欢
    • 2020-01-20
    • 2021-09-23
    • 2017-02-23
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 2020-03-24
    相关资源
    最近更新 更多