通过 NestJS 将类实现注入到基于接口的抽象控制器实现中

Jor*_*rdi 1 node.js typescript nestjs

我目前正在尝试使用 NestJS 注入进行设置,但在尝试运行服务器时遇到了错误。

我遇到的问题与我尝试将一个类注入到扩展抽象类的控制器中有关,并且我试图在构造函数中设置抽象类的属性。

控制器.ts

@Controller()
export class exampleController extends AbstractController {

  constructor(exampleClass: exampleInterface) {
    super(exampleClass);
  }

  @Get()
  getExample(): string {
    return 'Example';
  };
}
Run Code Online (Sandbox Code Playgroud)

AbstractController.ts

export abstract class AbstractController {

  private exampleClass: ExampleInterface;

  constructor(exampleClass: ExampleInterface) {
    this.exampleClass = exampleClass;
  };
Run Code Online (Sandbox Code Playgroud)

当我尝试运行我的服务器时,出现以下错误:

Error: Nest can't resolve dependencies of the ExampleController (?). Please make sure that the argument Object at index [0] is available in the AppModule context.

我已将类实现添加到 app.module 提供程序中,但即使这样,错误也会阻止我运行代码。

应用程序模块.ts

@Module({
  imports: [],
  controllers: [AppController, ExampleController],
  providers: [ExampleClass],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

示例类.ts

@Injectable()
export class ExampleClass implements ExampleInterface {

  doSomething(): void {
    console.log('Hello World!');
  };
};
Run Code Online (Sandbox Code Playgroud)

我已经尝试过不同的设置,并查看了其他一些 StackOverflow 问题,建议更改 app.module 中的提供程序,但我还没有找到适合我的设置。任何建议将不胜感激。

Jes*_*ter 5

Typescript 接口是一个编译时构造(当代码实际运行时它们根本不存在),因此 Nest 无法理解您尝试注入的参数。

您必须使用提供程序配置指定您自己的注入令牌,然后在ExampleController构造函数中使用它。

providers: [{ provide: 'ExampleToken', useClass: ExampleClass}]
Run Code Online (Sandbox Code Playgroud)

然后你可以使用ExampleToken(或任何在你的应用程序中有意义的东西)将它注入到你的控制器中

@Controller()
export class exampleController extends AbstractController {

  constructor(@Inject('ExampleToken') exampleClass: exampleInterface) {
    super(exampleClass);
  }

  @Get()
  getExample(): string {
    return 'Example';
  };
}
Run Code Online (Sandbox Code Playgroud)