Angular 5 Http Interceptors error when injecting service

后端 未结 8 911
北海茫月
北海茫月 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条回答
  •  隐瞒了意图╮
    2021-02-05 06:26

    So it turns out that if the service you inject into the Http Interceptor has a dependency on HttpClient, this leads to a cyclic dependency.

    Since my AuthService was a mix of all different logics (login/out, routing the user, saving/loading tokens, making api calls), I separated the part needed for the interceptors into its own service (just the user credentials & tokens) and now injecting it successfully into the Interceptor.

    export class AuthInterceptor implements HttpInterceptor {
        constructor(private credentials: CredentialsService) {}
        intercept(request: HttpRequest, next: HttpHandler): Observable> {
            const token = this.credentials.getToken();
            const api_key = this.credentials.getApiKey();
        }
    }
    
    export class CredentialsService {
        token: string;
        user: IUser;
        constructor(private http: HttpClient) {
            this.loadCredentialsFromStorage();
        }
    }
    

    This seems to work fine. Hope this helps someone.

提交回复
热议问题