【问题标题】:Angular providers and providedIn causing circular dependancyAngular提供者和providedIn导致循环依赖
【发布时间】:2023-03-13 00:33:01
【问题描述】:

我是 Angular 新手,所以我有一个非常基本的问题要问你们。

几个月前我开始了一个项目,当我创建一个服务时,我将它添加到我模块中的 providers 数组中。 像这样的:

import { Injectable } from '@angular/core';

import { MatchService } from '../../core/services/match.service';
import { Answer } from '../../core/models/answer';
import { Product } from '../../core/models/product';

@Injectable()
export class ScenarioMatchService {

  constructor(
    private matchService: MatchService
  ) { }

  find(product: Product, answers: Answer[]): string[] {
    var descriptions: string[] = [];

    answers.forEach(answer => {
      var formulas = answer.formulas;
      var match = this.matchService.matchProductUsingFormulas(product, formulas);
      if (match)
        descriptions.push(answer.text);
    })

    return descriptions;
  }
}

在我的模块中,我会有类似providers: [ScenarioMatchService] 的内容。这似乎工作正常。 我注意到前几天我在创建服务时得到了一个新的装饰:

@Injectable({ providedIn: 'root' })

所以我已经阅读了这篇文章: https://angular.io/guide/providers

现在,我有一个 CoreModule 我的单例服务所在的位置。因此,我认为将驻留在该文件夹中的所有服务更新为以下内容是个好主意:

@Injectable({
  providedIn: CoreModule
})

但现在我收到了来自 angular 的警告:

检测到循环依赖中的警告: src\app\core\animations\animations.component.ts -> src\app\core\services\animation.service.ts -> src\app\core\core.module.ts -> src\app\core\animations \animations.component.ts

我做错了什么导致这个?

【问题讨论】:

  • 您是否在AppModuleCoreModule 中提供了它?无论哪种方式,您都必须从模块文件中删除它,因为@Injectable({ providedIn: CoreModule }) 做同样的事情。只需在AppModule 中导入CoreModule
  • 这只是一个警告,大部分时间与您的导入有关,您可能将文件 A 中的类导入文件 B 和文件 B 中的类到文件 A。
  • 我试图将它们分开,所以不,我没有在应用程序模块或核心模块中提供任何东西。我只是在“核心”服务中有装饰器。
  • 我的意思是,例如,它声明一个组件依赖于一个服务(它被注入),它依赖于一个模块(使用装饰器),然后声明该组件

标签: angular


【解决方案1】:

错误消息清楚地表明您的配置中存在循环依赖。

core.module.ts providers 中删除您已配置的所有服务

@Injectable({
  providedIn: CoreModule
})

【讨论】:

    【解决方案2】:

    https://github.com/angular/angular-cli/issues/10170

    上面的文章解决了我的问题。 我将所有 @Injectable({ providedIn: CoreModule }) 替换为 @Injectable({ providedIn: 'root' }) 并且对于我想要延迟加载的任何服务都使用模块 providers 数组提供(即旧方式)

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2018-12-06
      • 1970-01-01
      • 2018-07-22
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      相关资源
      最近更新 更多