因为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()));发布于 2019-09-17 04:47:08
关于影响或者哪种方式更好,我不能说太多;但是,如果您正在寻找一种让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导入的。You can read more about it here。
https://stackoverflow.com/questions/57956510
复制相似问题