'What's the best way to run method of Component (Service) just after bootstrap running?
I'm using NestJS instance as microservice (without HTTP).
I need to run Component's method that is infinity loop with some business logic just after bootstrap initialization.
What is the best way to do it?
src/main.ts
import {NestFactory} from '@nestjs/core';
import {ApplicationModule} from './app.module';
import {Transport} from '@nestjs/microservices';
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
app.connectMicroservice({
transport: Transport.REDIS,
url: 'redis://:redis_pass@localhost:6379',
});
await app.startAllMicroservicesAsync();
// Probably here I must run startLoop method from app.service.ts
}
bootstrap();
src/app.service.ts
import { Component } from '@nestjs/common';
@Component()
export class AppService {
startLoop() {
let timerId = setTimeout(function loop() {
console.log('Loop process');
// Some business logic here
timerId = setTimeout(loop, 1000);
}, 1000);
}
}
Solution 1:[1]
I'd say that you should implement OnModuleInit interface. Read more about lifecycle hooks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | isherwood |
