nestjs - NestJS @Injectable 在全局对象中使用:使用“new injectionable”还是“app.use(injectable)”?
问题描述
由于 NestJS 允许注入,我想确保我编写最有效的代码。
我正在使用一个全局拦截器来包装我的应用程序响应和一个全局过滤器来处理异常。
//main.ts:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(app.get(LogService)));
app.useGlobalFilters(new ExceptionsFilter(app.get(LogService)));
//filter/interceptor.ts:
constructor(@Inject('LogService') private readonly logger: LogService) {}
在我的 main.ts 中,什么更有效?这两种选择有什么影响?有没有更好的办法?
//Option 1:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(app.get(LogService)));
app.useGlobalFilters(new ExceptionsFilter(app.get(LogService)));
或者
//Option 2:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(new LogService()));
app.useGlobalFilters(new ExceptionsFilter(new LogService()));
解决方案
关于影响或哪种方式更好,我不能说太多。但是,如果您正在寻找一种方法让 Nest 处理依赖项注入而不必这样做,您可以在 AppModule 中注册拦截器和过滤器,如下所示:
@Module({
imports: [/* your imports here*/],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: ResponseWrapperInterceptor
}, {
provide: APP_FILTER,
useClass: ExceptionsFilter
}
]
})
export class AppModule {}
从哪里导入APP_INTERCEPTOR
和APP_FILTER
导入@nestjs/core
。你可以在这里阅读更多关于它的信息。