如何从 NestJS 容器中获取对象

How to get an object from NestJS container

如何从nestjs中的容器获取注入对象?

这是 Spring (Java) 中的内容。我们可以像这样从容器中获取对象:

CustomerClass myClass = applicationContext.getBean("CustomerClass");

我们在 NestJS 中有这样的东西吗?

是的,存在。

这就是您从应用程序中检索名为 TaskService 的服务的方式。

const app = await NestFactory.createApplicationContext(AppModule);
const tasksService = app.get(TasksService);

当然,您应该始终考虑是否真的需要 NestJs 模块系统之外的服务实例。如果可能,留在应用程序内部并注入服务。