javascript - 将一个提供程序注入(inject)另一个提供程序,相同的模块 #1250

标签 javascript node.js typescript dependency-injection nestjs

我有一个服务/提供者,假设它在模块 A 中调用 ServiceA1,标记为 @Injectable()。 在同一模块中,我有另一个服务/提供者,假设它调用ServiceA2,标记为@Injectable()

我想在 ServiceA2 中注入(inject) ServiceA1 我尝试使用: my service

此代码抛出错误:serviceA1 undefined

我的模块.ts

module.ts

我是否必须创建另一个模块才能在 serviceA1 中使用 serviceA2

最佳答案

如果您直接通过类注入(inject)服务,则不需要 @Inject():

@Injectable()
export class ServiceA2 {
  constructor(private serviceA1: ServiceA1) {
  }

这与:

相同
@Injectable()
export class ServiceA2 {
  constructor(@Inject(ServiceA1) private serviceA1: ServiceA1) {
  }

请注意,您注入(inject)了 @Inject('ServiceA1') 而不是 @Inject(ServiceA1)。这是通过字符串标记而不是类来匹配的,因此无法解析。

如果您想通过字符串标记注入(inject)类,则需要在模块中声明提供程序,如下所示:

providers: [
    ServiceA2,
    {provide: 'ServiceA1', useClass: ServiceA1},
]

这也适用于同一模块。

关于javascript - 将一个提供程序注入(inject)另一个提供程序,相同的模块 #1250,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53088444/

相关文章:

reactjs - React-Table:在组件 ref 上调用 'getResolvedState()' 抛出异常

对象数组中的 Angular 更新对象

typescript - Gatsby:将 SASS 模块与 Typescript 结合使用

javascript - 是否可以创建一个 Chrome 扩展程序来执行属于正在浏览的页面的 javascript 函数?

javascript - 如何设置份数 getPrintParams()

javascript - FormArray 无效但不包含错误

javascript - Npm 提示 - 自定义验证和多行消息?

javascript - ActiveXObject 创建错误 "Automation server can' t 创建对象”

javascript - ER_PARSE_ERROR 您的 SQL 语法有错误 : Selecting entire table from MySQL

mysql - 如何改变 Node js 中的授权(权限)级别