最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Service in Global-interceptor in NEST Js - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited May 26, 2018 at 6:19 Muhammad Shaharyar asked May 24, 2018 at 7:58 Muhammad ShaharyarMuhammad Shaharyar 1,1041 gold badge9 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

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

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

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

This is listed in the official documentation, here.

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);  //
}

发布评论

评论列表(0)

  1. 暂无评论