Trying to repeat a http request after refresh token with a interceptor in angular 7

后端 未结 3 1917
时光说笑
时光说笑 2021-02-03 10:52

I\'m trying to automate the refresh token requests upon receiving an error 401 with angular 7.

Between that I do not find much documentation of how to do it with angular

3条回答
  •  遇见更好的自我
    2021-02-03 11:33

    You can do something like this :

    import { HttpErrorResponse } from '@angular/common/http';
    
    return next.handle(req).pipe(
      catchError((err: any) => {
        if (err instanceof HttpErrorResponse && err.status 401) {
         return this._authenticationService.refresh()
           .pipe(tap(
             (success) => {},
             (err) => {
               this._authenticationService.logOut();
               throw error;
             }
           ).mergeMap((res) => {
             this._authenticationService.processLoginResponse(res);
             newReq.headers.set("Authorization", "Bearer " + this._authenticationService.authResponse.token)
             return next.handle(newReq)
           });
        } else {
          return Observable.of({});
        }
      }
    ));
    

提交回复
热议问题