5

I want to use service in global interceptor.

my code look like this :

import { VariablesService } from '../app/modules/variables/variables.service';

@Interceptor()
export class globalInterceptor implements NestInterceptor {
  constructor(private service: VariablesService) {
    console.log('contructor running', service);  //getting null here
  }

and on server.ts first i was initializing like this :

app.useGlobalInterceptors(new globalInterceptor())

but after the injection of service i have to do some modification because parameters are needed now in globalInterceptor()

const variableService = await app.get<VariablesService>(VariablesService);
  app.useGlobalInterceptors(new globalInterceptor(variableService));

Now what the problem is I am getting service is null and I am unable to create the object of the service.

GitHub issue link

2 Answers 2

11

You can register a global interceptor directly from the module definition:

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: GlobalInterceptor,
    },
  ],
})
export class ApplicationModule {}

This is listed in the official documentation, here.

0
0

After that you must import VariablesService module in your current interceptor module for dipendancy injection

constructor(@Inject(VariablesService) private service: VariablesService) {
    console.log('contructor running', service);  //
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.