本文介绍了管道后订阅时Rxjs catchError不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 observable 来使用 API

I have created an observable to consume an API

可观察:-

    return this.http.post('/api/ApplicationUser/Login', loginDetails, httpOptions).pipe(
      map((result: any) => {
        localStorage.setItem('jwtToken', result.jwtToken);
        localStorage.setItem('refreshToken', result.refreshToken.value)
        localStorage.setItem('UserName', result.userName);
        return result;
      }),
      catchError((err: any) => {
        //this.userLogout()
        console.log('refresh error')
        return throwError(err);
      })
    );
  }

当我使用以下代码激活时,根据我的情况,以上代码运行良好,结果或抛出错误:-

Above code is working fine by results or throwing errors according to my situations when Iam activating with below code:-

    this.loginService.getNewRefreshToken().subscribe(
      (res => { console.log(res) }),
      (err => {
        this.loginService.userLogout()
        console.log(err)
      }),
      () => { console.log('subscription completed')},
    );

但我的问题是当我用下面的代码激活它时,它的 catchError 不起作用但结果很好.为什么 catchError 在以下情况下不起作用?

But my problem is when Iam activating it with below code its catchError not working but results are fine.Why catchError is not working in below case?

    return this.loginService.getNewRefreshToken().pipe(
      map((res: any) => {
        console.log(res);
      }),
      catchError((err: any) => {
        console.log(err);
        return throwError(err);
      })
    ).subscribe(
      (res => {
      console.log(res)
    }),
      (err => {
        console.log(err)
      })
      )

推荐答案

您的 getNewRefreshToken 函数处理异常,因此它不会传播到上游侦听器.

Your getNewRefreshToken function eats the exception hence it does not get propagated to upstream listeners.

尝试 throwError

 getNewRefreshToken(): Observable<any> {
   var loginDetails: LoginDetails = {
   email: localStorage.getItem('UserName'),
   grantType: 'refreshToken',
   password: '',
   refreshToken: localStorage.getItem('refreshToken')
  }

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'my-auth-token'
  }),
 };

return this.http.post('/api/ApplicationUser/Login', loginDetails, httpOptions).pipe(
  map((result: LoginResponse) => {
    localStorage.setItem('jwtToken', result.jwtToken);
    localStorage.setItem('refreshToken', result.refreshToken.value)
    localStorage.setItem('UserName', result.userName);
    return result;
  }),
  catchError((err: any) => {
    this.userLogout()
    console.log('refresh error')
    return throwError(err);  //<-- insert this
  })
);
}

示例 查看结果控制台.

这篇关于管道后订阅时Rxjs catchError不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-02 22:17