Run program on init

前端 未结 1 582
清酒与你
清酒与你 2020-12-11 20:44

I would create a program (script) that launches actions when it\'s get run, so I\'m not using routes in this program

I\'m using NestJS framework (requirement).

相关标签:
1条回答
  • 2020-12-11 20:51

    There are two ways to do this:

    A) 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();
      }
    }
      
    

    B) Execution Context

    Use the Execution Context to access any service in your main.ts:

    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      await app.listen(3000);
      const appService = app.get(AppService);
    }
    
    0 讨论(0)
提交回复
热议问题