相关疑难解决方法(0)

在 NestJs 中,如何根据其接口注入服务?

我有下一个模块:payment.module.ts

@Module({
  controllers: [PaymentController],
})
export class PaymentModule {}
Run Code Online (Sandbox Code Playgroud)

在下一个服务中,我想访问基于接口的服务

支付服务.ts

export class PaymentService {
   constructor(private readonly notificationService: NotificationInterface,
}
Run Code Online (Sandbox Code Playgroud)

通知.interface.ts

export interface NotificationInterface {
  // some method definitions
}
Run Code Online (Sandbox Code Playgroud)

通知.service.ts

@Injectable()
export class NotificationService implements NotificationInterface {
  // some implemented methods
}
Run Code Online (Sandbox Code Playgroud)

问题是我如何注入NotificationService基于NotificationInterface

javascript node.js typescript ecmascript-6 nestjs

3
推荐指数
2
解决办法
4243
查看次数

通过 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],
}) …
Run Code Online (Sandbox Code Playgroud)

node.js typescript nestjs

1
推荐指数
1
解决办法
3810
查看次数

标签 统计

nestjs ×2

node.js ×2

typescript ×2

ecmascript-6 ×1

javascript ×1