无法实例化循环依赖! HttpClient(" [ERROR - >]"):在./AppModule@-1:-1中的NgModule AppModule中

时间:2017-11-23 07:10:00

标签: angular angular-cli

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

// 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;
      }
    }

3 个答案:

答案 0 :(得分:2)

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

您可以做的是将Auth服务分成两部分:Auth包含大部分现有功能,AuthContextService具有getToken()功能(以及或许其他人)。您的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);
  }
}

答案 1 :(得分:0)

它是known issue,有几种可能的解决方法。它通常发生在您的auth拦截器服务中。

更改注入AuthService的方式对我有用,请参阅下面的代码段。请注意此处Injector的使用情况以及您AuthService函数直接注入intercept()的方式。

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,
};

答案 2 :(得分:0)

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

因此,如果您有关于 没有 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/