首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在全局对象中使用了NestJS @Injectable :使用'new injectable‘还是'app.use(injectable)'?

在全局对象中使用了NestJS @Injectable :使用'new injectable‘还是'app.use(injectable)'?
EN

Stack Overflow用户
提问于 2019-09-16 20:04:26
回答 1查看 348关注 0票数 0

因为NestJS允许注入,所以我想确保我写的代码是最有效的。

我使用一个全局拦截器来包装我的应用程序响应,并使用一个全局过滤器来处理异常。

代码语言:javascript
复制
//main.ts:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(app.get(LogService)));
app.useGlobalFilters(new ExceptionsFilter(app.get(LogService)));
代码语言:javascript
复制
//filter/interceptor.ts:
constructor(@Inject('LogService') private readonly logger: LogService) {}

在我的main.ts中,哪个更有效?这两个选项的影响是什么?有没有更好的方法?

代码语言:javascript
复制
//Option 1:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(app.get(LogService)));
app.useGlobalFilters(new ExceptionsFilter(app.get(LogService)));

代码语言:javascript
复制
//Option 2:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(new LogService()));
app.useGlobalFilters(new ExceptionsFilter(new LogService()));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-17 04:47:08

关于影响或者哪种方式更好,我不能说太多;但是,如果您正在寻找一种让Nest处理依赖注入的方法,以便不必这样做,您可以在AppModule中注册拦截器和过滤器,如下所示:

代码语言:javascript
复制
@Module({
  imports: [/* your imports here*/],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: ResponseWrapperInterceptor
    }, {
      provide: APP_FILTER,
      useClass: ExceptionsFilter
    }
  ]
})
export class AppModule {}

其中APP_INTERCEPTORAPP_FILTER是从@nestjs/core导入的。You can read more about it here

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57956510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档