Last active
July 25, 2018 11:00
-
-
Save Bidthedog/8285042fa5200108e7135b841e623b5d to your computer and use it in GitHub Desktop.
Angular 6 + RxJs 6 Refresh Token Interceptor - final retry cancels itself?
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
@Injectable() | |
export class HandleUnauthorisedRequestInterceptor implements HttpInterceptor { | |
constructor( | |
private securityService: SecurityService | |
) { } | |
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
console.log('intercepting ' + req.method + ' to ' + req.url); | |
// Ignore all security controller requests as they're all dealt with separately | |
if (req.url.indexOf('/security/') > -1) { | |
return next.handle(req); | |
} | |
// Handle 401 responses from all other responses - attempt to refresh token | |
// quietly. If refresh fails, log out and redirect | |
return next.handle(req) | |
.pipe( | |
retryWhen(error$ => { | |
return error$ | |
.pipe( | |
flatMap((error: HttpErrorResponse) => { | |
if (error.status === 401) { | |
console.log('401 received - attempting refresh'); | |
return from(this.securityService | |
.refreshAndHandle(); | |
} | |
console.log('throwing...'); | |
return Observable.throw({ error: 'No retries configured...' }); | |
}), | |
take(1) | |
); | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment