Rxjs catchError在管道后订阅时不起作用

时间:2019-09-19 05:03:55

标签: angular rxjs angular7

我创建了一个使用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);
      })
    );
  }

使用Iam激活以下代码时,根据我的情况,以上代码可以正常工作,结果也可以抛出错误:-

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

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

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

1 个答案:

答案 0 :(得分:0)

您的getNewRefreshToken函数会吃掉异常,因此不会传播到上游侦听器。

尝试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 
  })
);
}

Sample在控制台中查看结果。