Angular 9:无法实例化循环依赖

我正在重用HTTP通信服务,该服务在Angular 8下工作正常,但是在Angular 9下抛出以下错误:

Error: Cannot instantiate cyclic dependency! HttpService
    at throwCyclicDependencyError (core.js:8122)
    at R3Injector.hydrate (core.js:17206)
    at R3Injector.get (core.js:16960)
    at NgModuleRef$1.get (core.js:36337)
    at Object.get (core.js:33981)
    at getOrCreateInjectable (core.js:5880)
    at Module.ɵɵdirectiveInject (core.js:21115)
    at NodeInjectorFactory.DashboardComponent_Factory [as factory] (dashboard.component.ts:9)
    at getNodeInjectable (core.js:6025)
    at instantiateRootComponent (core.js:12788)
    at resolvePromise (zone-evergreen.js:798)
    at resolvePromise (zone-evergreen.js:750)
    at zone-evergreen.js:860
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:41640)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)
    at drainMicroTaskQueue (zone-evergreen.js:569)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
    at invokeTask (zone-evergreen.js:1621)

这是HTTP服务的代码:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class HttpService {

    url: string = 'http://localhost:8000/';

    constructor(private httpClient: HttpClient) { }

    public getTestCall() {
        return this.httpClient.get(this.url + 'test');
    }
}

这是使用HTTP服务的组件之一:

import { Component, OnInit } from '@angular/core';
import { HttpService } from 'src/app/services/http.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  constructor(private http: HttpService) { }

  ngOnInit(): void { }
}

使用[routerLink]指令和app-routing.module.ts在app.component.html中引用这些组件。 提前致谢!

评论
  • yeahlife
    yeahlife 回复

    I prefer declaring the HTTP Services as: @Injectable({ providedIn: 'root', }) and not providing them in any module.

    这样一来,从一开始就可以在整个应用程序上访问该服务,并且可能不会出现这样的错误。

    如果您将应用程序模块包括在问题中,那会更好。

  • 绳灵秋
    绳灵秋 回复

    如果您有多个模块: 问题可能是,在多个模块中提供了HttpService。

    在这种情况下: 解决方案可以创建一个新模块:HttpServiceModule:

    @NgModule({
      providers: [ HttpService ]
    })
    export class HttpServiceModule {}
    

    之后,您必须在所有其他模块中删除:提供程序:[... HttpService ...]