Lifecycle Events
There're 2 module lifecycle events, the OnModuleInit and OnModuleDestroy.
It's a good practice to use them for all the initialization stuff and avoid to put anything directly in the constructor.
The constructor should be used only to initialize the class members and inject the required dependencies.
JavaScript
TypeScript
TypeScript
import { Component, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
@Component()
export class UsersService implements OnModuleInit, OnModuleDestroy {
onModuleInit() {
console.log(`Module's initialized...`);
}
onModuleDestroy() {
console.log(`Module's destroyed...`);
}
}
TypeScript
import { Component } from '@nestjs/common';
@Component()
export class UsersService {
onModuleInit() {
console.log(`Module's initialized...`);
}
onModuleDestroy() {
console.log(`Module's destroyed...`);
}
}