javascript - Hur man använder Service i Global-interceptor i NEST Js


Jag vill använda tjänst i global interceptor.

min kod ser ut så här :

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
  }

och på server.ts först initierade jag så här :

app.useGlobalInterceptors(new globalInterceptor())

men efter injektionen av tjänsten måste jag göra några ändringar eftersom parametrar behövs nu i globalInterceptor()

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

Nu är problemet att jag får service som null och jag kan inte skapa objektet av tjänsten.

GitHub-ärendelänk

Svar #1

Du kan registrera en global interceptor direkt från moduldefinitionen:

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

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

Detta finns listat i den officiella dokumentationen, här.

Relaterade artiklar