Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Nestjs 如何在变量中注入内容?_Nestjs - Fatal编程技术网

Nestjs 如何在变量中注入内容?

Nestjs 如何在变量中注入内容?,nestjs,Nestjs,我在模块中提供了一项服务: import { Module } from '@nestjs/common'; import { SomethingService } from './something.service'; @Module({ providers: [SomethingService] }) export class SomethingModule {} 在另一个文件中,我想将此服务注入一个常量中。使用typedi我将执行以下操作: import { Container

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

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实现这一点?

Nest的自然DI系统通过
构造函数进行依赖注入。注入值通常如下所示:

@injetable()
导出类somesomeclass{
构造函数(私有只读somethingService:somethingService){}
}
Nest通过大量的反射,通过类名找出您正在注入的内容。如果出于某种原因,您需要执行以下操作:

@Injectable()
导出类somesomeclass{
@注入()
私人某物服务:某物服务;
}
Nest应该能够解决注入问题,尽管通常基于构造函数的注入是首选的,因为它更可靠,并且是大多数Nest应用程序的标准方法

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

@模块({
提供者:[SomethingService],
导出:[SomethingService],
})
导出类SomethingModule{}
@模块({
导入:[SomethingModule],
提供者:[其他服务],
})
导出类OtherModule{}
@Injectable()
出口类其他服务{
构造函数(私有只读somethingService:somethingService){}
}

您能再详细说明一下您想做什么吗?我不确定我是否理解
我想在常量中注入此服务
@JayMcDoniel我想在服务常量中注入某项服务的实例您想在其他提供商或控制器中执行此操作吗?或者你是想在Nest的DI系统之外做这件事?它在另一个提供商中