简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM