Run program on init

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 05:19:12

There are two ways to do this:

Execution Context

Use the Execution Context to access any service:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  const appService = app.get(AppService);
}

Lifecycle Event

Use a Lifecycle Event (similar to change detection hooks in Angular) to run code and inject the services needed for it, e.g.:

Service

export class AppService implements OnModuleInit {
  onModuleInit() {
    console.log(`Initialization...`);
    this.doStuff();
  }
}

Module

export class ApplicationModule implements OnModuleInit {

  constructor(private appService: AppService) {
  }

  onModuleInit() {
    console.log(`Initialization...`);
    this.appService.doStuff();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!