Angular 5 Http Interceptors error when injecting service

后端 未结 8 923
北海茫月
北海茫月 2021-02-05 05:43

I am receiving the following strange dependency injection behavior when using custom HttpInterceptors in angular 5+.

The following simplified code works fine:

         


        
8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 06:14

    I got a similar issue with the same design of an auth service coupled with an interceptor.

    @Injectable() AuthInterceptorService {
        constructor (authApi: AuthApiService) {}
        handle () {...do the job}
    }
    
    @Injectable() AuthApiService {
       constructor () {
           // ...do some setup with a request, such as to get current session
           // that leads to an indirect circular between 2 constructors. 
       }
    

    }

    In my case, i found the cause is that I try to start a http request in the auth service's constructor. At that point the injector seems haven't completed the registration of the auth service's instance, while the http client captures the new request and tried to instantiaze the interceptor again, since the previous interceptor instance was stuck in its constructor on the call stack too!

    That recursive invoke with two constructors, breaks the singleton pattern of the injector and leads to out of call stack.

提交回复
热议问题