Skip to content Skip to sidebar Skip to footer

Run Program On Init

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). Actually I'm trying to

Solution 1:

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

exportclassAppServiceimplementsOnModuleInit {
  onModuleInit() {
    console.log(`Initialization...`);
    this.doStuff();
  }
}

Module

exportclassApplicationModuleimplementsOnModuleInit {
  
  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);
}

Post a Comment for "Run Program On Init"