HttpInterceptor->Service->HttpClient Cyclic Dependency

后端 未结 3 1527
借酒劲吻你
借酒劲吻你 2020-12-10 06:09

So I have my authentication service, AuthService, that basically has two methods, one that gets a new token from the server, given a username and a password

相关标签:
3条回答
  • 2020-12-10 07:01

    Update 08/02/2018 - angular 5.2.3

    Just an update on this: this was fixed in angular 5.2.3

    https://github.com/angular/angular/blob/master/CHANGELOG.md#bug-fixes-2

    So you can directly inject services that depend on HttpClient in HttpInterceptors

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
    
        constructor(private auth: AuthService) 
    
    0 讨论(0)
  • 2020-12-10 07:01

    I was running into the same or a similar issue using Angular 6.1.10. I simply instantiated HttpClient myself inside the service that need to be injected into an HttpInterceptor:

    @Injectable()
    export class AuthService {
    
      private http: HttpClient;
    
      constructor(httpBackend: HttpBackend) {
        this.http = new HttpClient(httpBackend);    
      }
    }
    

    That broke the infinite loop issue in my case.

    0 讨论(0)
  • 2020-12-10 07:09

    Try setting this.auth with a timeout:

    constructor(private injector: Injector) {
      setTimeout(() => {
        this.auth = this.injector.get(AuthService);
      })
    }
    

    The bug report you have linked to has since been updated, with an alternative workaround (retrieving AuthService in the intercept function / and not setting it in the constructor): https://github.com/angular/angular/issues/18224#issuecomment-316957213

    0 讨论(0)
提交回复
热议问题