Angular 服务间通信和 'circular dependency detected' 警告

Angular service to service communication and 'circular dependency detected' warnings

很简单,我有一个 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

这两个服务都在应用程序模块提供程序数组中声明。为什么我会得到循环依赖?

您在 UserService 中注入了 AuthenticationService 并且在 AuthenticationService[ 中注入了 UserService =26=]!不要这样做!

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

在大多数情况下,将您的方式重构为没有循环依赖性是相当容易的,所以这就是为什么它是一个警告,但最终,我认为摆脱这些类型的模式是一种很好的做法。

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

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