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