Jan Wytze
Jan Wytze

Reputation: 3497

Angular 4 HTTP request from HTTP interceptor

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?

Upvotes: 3

Views: 3898

Answers (1)

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18429

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);
    });
  }
}

Upvotes: 6

Related Questions