3

I am trying to update Http to the newer HttpClient.

For JWT refreshing I extended the Http class and override the request() method(https://stackoverflow.com/a/45750985/2735398).
Now I want to do the same with interceptors.

This is the interceptor I have right now:

export class JwtRefreshInterceptor implements HttpInterceptor { public constructor( private httpClient: HttpClient, ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).catch((error: HttpErrorResponse) => { if (error.status === 401) { return this.httpClient.post(environment.base_uri + 'auth/refresh', {}).flatMap((response) => { // get token from response. // put token in localstorage. // add token to the request. // Do the request again with the new token. return next.handle(request); }); } return Observable.throw(error); }); } } 

The problem is that I can't inject HttpClient because I get an error:

Provider parse errors: Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1 

With extending Http I could just call this.post() because I was working in the Http instance itself. But with the interceptors this can't be done.

How can I make an HTTP request inside an interceptor?

1 Answer 1

6

You can inject Injector from @angular/core and get the dependency when needed:

export class JwtRefreshInterceptor implements HttpInterceptor { constructor(private injector: Injector) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).catch((error: HttpErrorResponse) => { if (error.status === 401) { const http = this.injector.get(HttpClient); return http.post(environment.base_uri + 'auth/refresh', {}).flatMap((response) => { // get token from response. // put token in localstorage. // add token to the request. // Do the request again with the new token. return next.handle(request); }); } return Observable.throw(error); }); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

If I import { Injector } from "@angular/core" and then add "private injector: Injector" to the constructor I get the following..... Uncaught Error: Can't resolve all parameters for ResponseInterceptor: (?) -- Do I need to inject it in the app.module somehow?
I just what i was finding, because i am implementing a token refresh :O

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.