7

在我的 Angular 项目中启用 ivy 后,一切都会编译,但是在浏览器中启动应用程序时,我在应用程序引导期间收到以下错误:

Error: Cannot instantiate cyclic dependency! ApplicationRef
    at throwCyclicDependencyError (core.js:5208)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (core.js:11763)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (core.js:11590)
    at injectInjectorOnly (core.js:648)
    at ɵɵinject (core.js:653)
    at injectArgs (core.js:730)
    at Object.factory (core.js:11858)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (core.js:11767)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (core.js:11590)
    at injectInjectorOnly (core.js:648)

我正在努力找出循环依赖在哪里以及为什么在不使用常春藤时它可以正常工作。我尝试使用 madge (madge --circular --extensions ts ./) 但没有找到循环依赖。

编辑:我已经手动完成了所有服务并验证它们之间没有循环依赖

4

3 回答 3

3

事实证明,在我的 app.module 提供程序中,我在 @Injectable() 中有一个带有 {provideIn: 'root'} 的类,删除了它修复了它。

providers: [
    { provide: ErrorHandler, useClass: AppErrorHandler }
]

@Injectable({ providedIn: 'root' })
export class AppErrorHandler implements ErrorHandler {

@Injectable()
export class AppErrorHandler implements ErrorHandler {

我不知道为什么在 ivy 之前这不是问题,即使使用 AoT

于 2019-10-11T19:14:19.747 回答
1

You must be injecting the Router somewhere in any of your services which uses @Injectable. So you got two options:

Solution 1

Remove the dependency of router: Router from your service constructor.

Solution 2

Upgrade to a minimum Angular 9.0.3 which fixes this issue of cyclic dependency.

(Got fixed in this MR https://github.com/angular/angular/pull/35642)

于 2020-03-04T08:06:55.087 回答
0

I had the same error after update Angular project. Before update i had like below and it works until Angular was updated:

@NgModule({
  imports: [
    ...,
    BrowserModule
  ],
  declarations: [ErrorComponent],
  providers: [
    {
      provide: ErrorHandler,
      useClass: ErrorHandlerService,
    }
  ]  
})
export class ErrorModule { }

After update, to fix this error i have changed this module to like so:

@NgModule({
  imports: [
    ...,
    BrowserModule
  ],
  declarations: [ErrorComponent]
})
export class ErrorModule { 
  public static forRoot(): ModuleWithProviders {
    return {
      ngModule: ErrorModule,
      providers: [
        {provide: ErrorHandler, useClass: ErrorHandlerService}
      ]
    };
  }
}
于 2019-11-15T21:35:58.023 回答