【问题标题】:How to use Service in Global-interceptor in NEST Js如何在 NEST Js 的 Global-interceptor 中使用 Service
【发布时间】:2018-11-03 08:46:27
【问题描述】:

我想在全局拦截器中使用服务。

我的代码如下所示:

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
  }

server.ts 上,我首先是这样初始化的:

app.useGlobalInterceptors(new globalInterceptor())

但是在注入服务之后我必须做一些修改,因为globalInterceptor()中现在需要参数

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

现在问题是我得到的servicenull,我无法创建服务对象。

GitHub issue link

【问题讨论】:

    标签: javascript typescript interceptor nestjs


    【解决方案1】:

    您可以直接从模块定义中注册一个全局拦截器:

    import { Module } from '@nestjs/common';
    import { APP_INTERCEPTOR } from '@nestjs/core';
    
    @Module({
      providers: [
        {
          provide: APP_INTERCEPTOR,
          useClass: GlobalInterceptor,
        },
      ],
    })
    export class ApplicationModule {}
    

    这在官方文档中列出,here

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 2020-04-27
      • 2021-05-05
      • 2021-08-28
      相关资源
      最近更新 更多