如何将字面类型用作Nestjs

问题描述 投票:0回答:2

我在我的服务上有一种字面类型作为构造函数参数:

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 {}
dependency-injection service nestjs
2个回答
5
投票

在Nestjs,您需要通过

providers
提供构造函数参数。 Nest使用
classes
通常知道可以使用哪些注入令牌,因为类Typescript和JavaScript中的类都持续存在。但是,您可以使用带有自己的注入令牌和自定义值的
@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无法解决,则可以绕过注入,那么您仍然可以轻松地使用默认值,就像以前的默认值
    


0
投票
@Injectable()

装饰器引起的,该装饰器使该类在应用程序开始时由Nestjs注入,如果您打算使用不同的参数实例化类,则最好使用

new Class()
语句。 它在
Logger
[class] [1]中的一种用途,此类不是注射剂,并且需要每次需要使用它时进行实例化。
示例:

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

然后,在另一个类中。

#import the appService, Myservice and MyType export class MyClass { myService = new MyService(appservice, myType) }
the hoping有帮助!

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.