【问题标题】:Angular service to service communication and 'circular dependency detected' warningsAngular 服务到服务通信和“检测到循环依赖”警告
【发布时间】:2019-09-19 06:32:07
【问题描述】:

很简单,我有一个 AuthenticationService 和一个 UserService。 UserService 包含在 AuthenticationService 中。然后当我在 UserService 中使用 AuthenticationService 时:

constructor(private authService: AuthenticationService){}

我明白了:

Circular dependency detected:
src/app/core/authentication/authentication.service.ts -> src/app/shared/services/user.service.ts -> src/app/core/authentication/authentication.service.ts

这两个服务都在应用模块提供者数组中声明。为什么会出现循环依赖?

【问题讨论】:

  • 因为正如你所说,你在UserServiceUserService中注入了AuthenticationServiceAuthenticationService
  • Angular 不知道先创建哪个。

标签: angular typescript circular-dependency


【解决方案1】:

您在 UserService 中注入了 AuthenticationService,在 AuthenticationService 中注入了 UserService!不要这样做!

这里出现的循环依赖与直接或间接相互导入的文件有关。这在软件中并不少见,但结果可能会有所不同。这并不一定意味着会发生错误,但重要的是要浮出水面,因为根据用例可能会发生错误。

在大多数情况下,重构无循环依赖的方式是相当容易的,这就是为什么它是一个警告,但最终,我认为摆脱这些类型的模式是一种好习惯。

对于隐藏警告,您应该将 showCircularDependencies 添加到您的 .angular-cli.json 中:

 "defaults": {
    "build": {
      "showCircularDependencies": false
    }
  }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-11-21
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2018-11-20
相关资源
最近更新 更多