相关疑难解决方法(0)

注入服务时Angular 5 Http Interceptors错误

在角度5+中使用自定义HttpInterceptors时,我收到以下奇怪的依赖注入行为.

以下简化代码工作正常:

    export class AuthInterceptor implements HttpInterceptor {
        constructor(private auth: AuthService) {}

        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            const token = this.auth.getToken();
            return next.handle(req);
        }
    }
    export class AuthService {
        token: string;
        constructor() {
          console.log('AuthService.constructor');
        }
    }
Run Code Online (Sandbox Code Playgroud)

然而....

AuthService具有1个或更多依赖性时,例如

   export class AuthService {
      token: string;
      constructor(private api: APIService) {
         console.log('AuthService.constructor');
      }
   }
Run Code Online (Sandbox Code Playgroud)

angular尝试重复创建新实例,AuthService直到收到以下错误:

日志显示AuthService.constructor消息~400次

Cannot instantiate cyclic dependency! HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule

app.component.html:44错误RangeError:超出最大调用堆栈大小

然后我尝试使用Injector类注入服务 -

 export class AuthService {
      token: …
Run Code Online (Sandbox Code Playgroud)

dependency-injection angular-http-interceptors angular

15
推荐指数
2
解决办法
1万
查看次数