dependency-injection - 如何在 NestJS 中使用文字类型作为服务构造函数参数

标签 dependency-injection service nestjs

我的服务中有一个文字类型作为构造函数参数:

export type MyType = 'val1' | 'val2';

@Injectable()
export class MyService {
  myType: MyType;
  constructor(private appService: AppService, private myType: MyType = 'val2') {
    this.myType = myType;
  }
}

构建时间有误

Nest can't resolve dependencies of the MyService (AppService, ?). Please make sure that the argument String at index [1] is available in the AppModule context.

Potential solutions:
- If String is a provider, is it part of the current AppModule?
- If String is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing String */ ]
  })

你会如何解决这个问题?

那是我的 AppModule:

@Module({
  imports: [HttpModule],
  controllers: [AppController],
  providers: [AppService, MyService, HttpClient],
})
export class AppModule {}

最佳答案

使用 NestJS,您需要通过 providers 提供构造函数参数。 Nest 通常使用 classes 来了解要使用的注入(inject) token ,因为类在 Typescript 和 JavaScript 中都存在。但是,您可以将 @Inject() 装饰器与您自己的注入(inject) token 和自定义值一起使用,以确保 Nest 正确注入(inject)该值。这看起来像这样:

@Module({
  providers: [
    MyService,
    {
      provide: 'MyToken', // this can be a symbol or a string
      useValue: 'val2',
    }
    AppService,
  ],
})
export class AppModule {}
export type MyType = 'val1' | 'val2';
@Injectable()
export class MyService {


  constructor(
    private appService: AppService,
    // this token MUST match exactly to the one in the `provide` property of the custom provider
    @Inject('MyToken') private myType: MyType
  ) {}
}

如果您想添加其他依赖项,只需确保它们对模块可用即可。

另一种选择是将 myType 标记为 @Optional() 这将允许 Nest 在无法解析的情况下绕过注入(inject),然后您仍然可以轻松地使用默认值和以前一样的值(value)

关于dependency-injection - 如何在 NestJS 中使用文字类型作为服务构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60924868/

相关文章:

dependency-injection - 为什么用这么多术语来表达同样的事情? IoC 和 DIP

java - Mapsruct 类和 @Service 类没有 @Autowired

jenkins - 如何在浏览器中访问Kubernetes NodePort服务?

android - 使用来自多个模块 dagger 2.11 android 的依赖项

c++ - 如何在不破坏主框架的情况下终止 wxWidgets 消息循环?

c# - (重新)从我的 C# 代码中启动 Windows 服务不起作用

可以与其他应用程序交互的 Android 服务

node.js - `repository.create` 去除既是数组又是嵌入对象的列的值

sql - 使用 NestJS 执行自定义查询的正确方法是什么?

typescript - NestJS - 如何将图像上传到 aws s3?