【问题标题】:Cannot instantiate cyclic dependency! HttpClient ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1无法实例化循环依赖! HttpClient ("[ERROR ->]"): 在 ./AppModule@-1:-1 中的 NgModule AppModule
【发布时间】:2018-05-07 01:36:00
【问题描述】:

我已经实现了一个拦截器来添加我可以制作 seucred api 的授权标头。 在任何应用程序模块中注入此服务时出现错误 // "无法实例化循环依赖!HttpClient("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1"

// auth拦截器添加授权承载

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Auth } from './auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(public auth: Auth) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}


// Auth service

    import { Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

    @Injectable()
    export class Auth {
      // Store profile object in auth class
      userProfile: Object;
      public token: string;
      constructor(private router: Router, private http: HttpClient) {
          // set token if saved in local storage
          const currentUser = JSON.parse(localStorage.getItem('currentUser'));
          this.token = currentUser;
      }
      login(username: string, password: string) {
        const headers = new HttpHeaders()
          .set('Content-Type', 'application/x-www-form-urlencoded')
          .set('Accept', 'application/json');
        const params = new HttpParams().set('username', username).set('password', password)
          .set('grant_type', 'password');
        return this.http.post('http://rrrrr/token', params.toString(),
          { headers }).subscribe(data => {
            this.token = data['access_token'];
          console.log(this.token);
        },
        err => {
          console.log('Error occured');
        });
      }
      getToken() {
        return this.token;
      }
      logout(): void {
          // clear token remove user from local storage to log user out
          this.token = null;
          localStorage.removeItem('currentUser');
      }
      public authenticated(): boolean {
        // Check whether the current time is past the
        // access token's expiry time
        const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
        return new Date().getTime() < expiresAt;
      }
    }

【问题讨论】:

  • 您的Auth 服务是否依赖于HttpClient?如果是这样,那么这就是一个循环依赖。
  • 是的,我该如何解决这个问题

标签: angular angular-cli


【解决方案1】:

您的Auth 服务依赖于HttpClient,这导致了循环依赖。

您可以做的是将您的Auth 服务分成两部分:一个具有大部分现有功能的Auth,另一个具有您的getToken() 功能(可能还有其他功能)的AuthContextService。然后,您的 Auth 服务可以依赖于您的 AuthContextService,您的 AuthInterceptor 也可以。

编辑:添加一些代码来尝试解释

@Injectable()
export class AuthContextService {
    // With getToken() in here, and not in Auth, you can use it in AuthInterceptor
    getToken(): string {
        return 'however you get your token';
    }   
}

@Injectable()
export class Auth {
    constructor (private http: HttpClient, private authContext: AuthContextService) {}

    authenticate(username: string, password: string) {
        // Do stuff
    }

    // Whatever other functions you already have on Auth.
}

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(public authContext: AuthContextService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.authContext.getToken()}`
      }
    });
    return next.handle(request);
  }
}

【讨论】:

  • 真的很难听懂你的回答。如果你能帮助我,那就太好了
  • 添加了一些代码。希望这有助于解释更多。
  • 那么我在哪里注入所有这些服务??
  • 在构造函数中,如图所示。当然,您还需要将它们作为提供者添加到您的模块中。您已经为您的Auth 服务做到了这一点,所以我假设您会知道如何...
  • 我看到你在auth服务中注入了AuthContextService,什么也没做。
【解决方案2】:

这是一个known issue,有几种可能的解决方法。它通常发生在您的身份验证拦截器服务中。

更改注入 AuthService 的方式对我有用,请参阅下面的代码 sn-p。请注意此处Injector 的用法以及在intercept() 函数中直接注入AuthService 的方式。

import { Injectable, Injector } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HTTP_INTERCEPTORS,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from 'app/services/auth/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private injector: Injector) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    // inject your AuthService here using Injector
    const auth = this.injector.get(AuthService);
    const authHeader = `Bearer ${auth.getToken()}`;
    const authReq = req.clone({
      headers: req.headers.set('Authorization', authHeader),
    });
    return next.handle(authReq);
  }
}

export const AuthHttpInterceptor = {
  provide: HTTP_INTERCEPTORS,
  useClass: AuthInterceptor,
  multi: true,
};

【讨论】:

  • 那么它有什么作用呢? export const AuthHttpInterceptor = { 提供:HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, };
  • 您应该将其导入您的@NgModule 并像providers: [AuthHttpInterceptor] 一样提供它以及您​​正在使用的其他服务。详情请见this official doc
  • 我试过了,错误消失了。实现此功能后,对访问令牌的调用将失败。
  • the call to access token fails 是什么意思?你可以再详细一点吗?由于错误消失了,这可能与您的 AuthService 有关,这是另一个讨论的主题
  • 您好,我想实现拦截器来访问授权的api,但这正在修改我在auth服务中的登录方法。请参阅我的问题中发布的身份验证代码。
【解决方案3】:

这种循环依赖的一个常见原因! HttpClient ERROR 通常与 NullInjectorError 相关联。

因此,如果您有一个关于 No provider for HttpClient! 的伴随记录错误,我相信这个解决方案会有所帮助:

  1. 打开 Angular 应用的 app.module.ts 文件。
  2. 从 @angular/common/http 导入 HttpClientModule。
  3. 将 HttpClientModule 添加到 @NgModule 导入数组。

您的 AppModule 应如下所示

import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

HttpClient 是 Angular 通过 HTTP 与远程服务器通信的机制。您可以查看此链接以获取更多信息https://www.thecodebuzz.com/angular-null-injector-error-no-provider-for-httpclient/

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 2019-01-10
    • 1970-01-01
    • 2016-11-14
    • 2017-05-05
    • 2021-01-29
    • 2019-12-03
    • 1970-01-01
    • 2018-05-09
    相关资源
    最近更新 更多