Angular 5 Http Interceptors error when injecting service

后端 未结 8 945
北海茫月
北海茫月 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:17

    you need to add Injector into constructor and inject AuthService via injector

    export class AuthInterceptor implements HttpInterceptor {
                constructor(private inj: Injector) {}
    
                intercept(req: HttpRequest, next: HttpHandler): Observable> {
                    const auth = this.inj.get(AuthService);
                    const token = this.auth.getToken();
                    return next.handle(req);
                }
            }
    

    don't forget import

    import {Injector} from '@angular/core';
    

提交回复
热议问题