Created
August 21, 2019 07:59
-
-
Save donaldpipowitch/c71055bc77ab17f65eaf90b04d36e433 to your computer and use it in GitHub Desktop.
Try to refresh token once on 401 with RxJS and Angular Http Interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { | |
HttpEvent, | |
HttpInterceptor, | |
HttpHandler, | |
HttpRequest, | |
HttpErrorResponse, | |
HttpClient | |
} from '@angular/common/http'; | |
import { Observable, throwError } from 'rxjs'; | |
import { flatMap, catchError } from 'rxjs/operators'; | |
import { tokenUrl } from './config'; | |
@Injectable() | |
export class UnauthorizedInterceptor implements HttpInterceptor { | |
constructor(private http: HttpClient) {} | |
// for every 401 we try to refresh tokens once | |
intercept( | |
req: HttpRequest<unknown>, | |
next: HttpHandler | |
): Observable<HttpEvent<unknown>> { | |
return next.handle(req).pipe( | |
catchError((err) => { | |
if ( | |
err instanceof HttpErrorResponse && | |
err.status === 401 && | |
err.url !== tokenUrl | |
) { | |
return this.http.get(tokenUrl).pipe(flatMap(() => next.handle(req))); | |
} else { | |
return throwError(err); | |
} | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment