我的服务中有一个文字类型作为构造函数参数:
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/