Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

typescript - angular 4.3x dynamic http interceptor

I followed this article from medium to create a http interceptor which lets me add headers to each http call

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

The article uses the authService to get a token dynamically. However as soon as I inject HttpClient into the AuthService I get a circular injection error.

Are there other ways i can dynamically adjust the interceptor?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A conventional way to avoid circular dependencies in both AngularJS and Angular is to get another provider instance in-place and not on provider instantiation:

export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService, public injector: Injector) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const httpClient = injector.get(HttpClient);
    ...
  }
}

Notice that if the interceptor applies to all HttpClient requests, it will be applied to the one that is done inside the interceptor itself and likely result in infinite recursion. In order to avoid this the request can be marked to skip the interceptor (e.g. via custom header).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...