I am using Angular 2 with TypeScript on the front-end. I am trying to implement a http interceptor that is setting the authorization header on each request. If the access token expires I am trying to retry the request, get a new access token with the refresh token and change the header of the current request, before the retry.
How to update the request header in the retryWhen operator?
For example here is the HttpInterceptor:
export class HttpInterceptor extends Http { get(url: string, options?: RequestOptionsArgs): Observable<Response> { return super.get(url, this.setRequestAuthorizationHeader(options)).retryWhen((errors: any) => this.errorHandler(errors)); } private setRequestAuthorizationHeader(options?: RequestOptionsArgs): RequestOptionsArgs { // some checks // get accessToken from localStorage options.headers.append('Authorization', 'Bearer ' + accessToken); } private errorHandler(errors) { return errors.switchMap((err) => { if (err.status === 401) { let closedSubject = new Subject(); this.authenticationService.refreshToken() .subscribe(data => { // How to update authorization header? This doesn't work. this.defaultOptions.headers.append('Authorization', 'Bearer ' + data.accessToken); closedSubject.next(); }); return <any>closedSubject; } else { return Observable.throw(err.json()); } }); } }
authenticationServiceuses Http too), you will end up in circular dependencyHttpInterceptorneedsauthenticationServicethat needsHttpInterceptor.catchinstead ofretryWhen, the later one will replay the sameObservable...