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

sre*_*moh 4 service dependency-injection nestjs

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

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

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

我在构建时遇到错误

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 */ ]
  })
Run Code Online (Sandbox Code Playgroud)

你会如何解决这个问题?

那是我的应用程序模块:

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

Jay*_*iel 5

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

@Module({
  providers: [
    MyService,
    {
      provide: 'MyToken', // this can be a symbol or a string
      useValue: 'val2',
    }
    AppService,
  ],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
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
  ) {}
}
Run Code Online (Sandbox Code Playgroud)

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

另一个选项是标记myType@Optional(),如果无法解析,这将允许 Nest 绕过注入,然后您仍然可以像以前一样轻松地使用默认值