Home > Software engineering >  How to use Service in a class that implements OnApplicationShutdown interface in NestJS
How to use Service in a class that implements OnApplicationShutdown interface in NestJS

Time:10-12

The service that I am trying to use is from an external library which has a global fields defined within itself, that I use in different modules.

I've tried to inject the service within a constructor but its value is undefined when it is called.

Content of shutdown.hook.ts:

export class AppShutdownHook implements OnApplicationShutdown {
    constructor(
        private fooService: FooService
    ) {}

    async onApplicationShutdown(signal: string) {
        if (signal === "SIGTERM") {
            this.fooService.getFooField();
        }
    }
}

Content of main.ts:

app.enableShutdownHooks();

Also, I tried to initialize the service as a class property, but it creates another instance of a Service class, which has different values of global ones.

export class AppShutdownHook implements OnApplicationShutdown {
    private fooService = new FooService();
    ...
}

CodePudding user response:

You need to decorate AppShutdownHook with @Injectable() so that Nest can read the metadata of the constructor and properly do the Dependency Injection you're expecting.

  • Related