我在一个模块中提供了一个服务:
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来实现这一点?
发布于 2020-03-04 03:35:55
Nest的自然依赖注入系统通过constructor进行依赖注入。注入值通常如下所示:
@Injcetable()
export class SomeAwesomeClass {
constructor(private readonly somethingService: SomethingService) {}
}Nest通过大量的反射,找出您通过类名注入的内容。如果您出于某种原因而需要使用injection to a property,您可以这样做:
@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) {}
}https://stackoverflow.com/questions/60514162
复制相似问题