首页 > 解决方案 > 如何在变量中注入一些东西?

问题描述

我在模块中提供了一项服务:

import { Module } from '@nestjs/common';
import { SomethingService } from './something.service';

@Module({
  providers: [SomethingService]
})
export class SomethingModule {}

在另一个文件中,我想将此服务注入一个常量。我typedi会做以下事情:

import { Container } from 'typedi';
const service = Container.get(SomethingService);

如何使用 Nest.js 实现这一目标?

标签: nestjs

解决方案


Nest 的自然 DI 系统通过constructor. 注入值通常如下所示:

@Injcetable()
export class SomeAwesomeClass {

  constructor(private readonly somethingService: SomethingService) {}
}

Nest 通过大量反射找出您通过类名注入的内容。如果您出于某种原因需要对属性进行注入,您可以执行以下操作:

@Injectable()
export class SomeAwesomeClass {

  @Inject()
  private somethingService: SomethignService;
}

Nest应该能够解决注入问题,尽管通常首选基于构造函数的注入,因为它更可靠,并且是大多数 Nest 应用程序的标准方法。

确保在您的模块元数据中,您也导出了提供程序,然后将提供程序的模块导入到将注入提供程序的模块中。例如

@Module({
  providers: [SomethingService],
  exports: [SomethingService],
})
export class SomethingModule {}
@Module({
  imports: [SomethingModule],
  providers: [OtherService],
})
export class OtherModule {}
@Injectable()
export class OtherService {
  constructor(private readonly somethingService: SomethingService) {}
}

推荐阅读