簡體   English   中英

在 Nestjs 的過濾器中注入服務

[英]inject services inside filters in nestjs

我正在嘗試在我創建的以下異常處理程序中注入nestjs-config

import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common';
import { HttpException } from '@nestjs/common';
import { InjectConfig } from 'nestjs-config';

@Injectable()
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(
    @InjectConfig()
    private readonly config,
  ) {
    this.config = config.get('errors');
  }
  catch(exception: HttpException, host: ArgumentsHost) {
    // some code here that calls this.config
  }
}

但它返回未定義:類型錯誤TypeError: Cannot read property 'get' of undefined

這是異常處理程序的全局定義方式:

const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);

好的,我剛剛意識到在您的代碼中您正在容器外部創建過濾器,因此未注入 ConfigService。 有幾種方法可以解決這個問題。

ConfigService.load(path.resolve(__dirname, 'config', '*.ts'))

const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalFilters(new HttpExceptionFilter(ConfigService));
await app.listen(3000);

或者

const app = await NestFactory.create(AppModule, {cors: true});
const config = app.get<ConfigService>(ConfigService);
app.useGlobalFilters(new HttpExceptionFilter(config));
await app.listen(3000);

取決於你的 AppModule 看起來像這樣

@Module({
    imports: [ConfigModule.load(path.resolve(__dirname, 'config', '*.ts')],
})
export AppModule {}

或者像這樣:

const app = await NestFactory.create(AppModule, {cors: true});
const httpExceptionFilter = app.get(HttpExpectionFilter);
app.useGlobalFilters(httpExpectionFilter);

通過調用 ConfigService 來解決它,如下所示:

export class HttpExceptionFilter implements ExceptionFilter {

  constructor(private readonly config: ConfigService) {
    this.config = ConfigService.get('errors');
  }
  catch(exception: HttpException, host: ArgumentsHost) {
    // some code here that calls this.config
  }
}

對於 Nestjs V8,您可以將其放在 AppModule 提供程序中:

{
  provide: APP_FILTER,
  useClass: HttpExceptionFilter,
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM