NestJS 是一个用于构建高效、可扩展的 Node.js 服务器端应用程序的框架。它基于 Express.js 和 Fastify,并且使用了现代 JavaScript 或 TypeScript。拦截器(Interceptor)是 NestJS 中的一个核心概念,允许你在方法调用前后执行自定义逻辑。
在 NestJS 中,拦截器可以注入并使用服务。以下是如何在非全局拦截器内部使用服务的示例:
假设我们有一个 LoggingService
用于记录日志:
import { Injectable } from '@nestjs/common';
@Injectable()
export class LoggingService {
log(message: string) {
console.log(`[LOG]: ${message}`);
}
}
接下来,创建一个拦截器 LoggingInterceptor
并在其中使用 LoggingService
:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LoggingService } from './logging.service';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(private readonly loggingService: LoggingService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const now = Date.now();
return next
.handle()
.pipe(
tap(() => {
this.loggingService.log(`${context.getClass().name}.${context.getHandler().name} ${Date.now() - now}ms`);
}),
);
}
}
在控制器中使用这个拦截器:
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { LoggingInterceptor } from './logging.interceptor';
import { LoggingService } from './logging.service';
@Controller('example')
export class ExampleController {
constructor(private readonly loggingService: LoggingService) {}
@Get()
@UseInterceptors(new LoggingInterceptor(this.loggingService))
getExample() {
return 'This is an example response';
}
}
原因:可能是因为拦截器没有正确地通过依赖注入获取服务实例。
解决方法:
LoggingService
已经在模块中声明并提供。@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(private readonly loggingService: LoggingService) {}
// ...
}
LoggingService
:import { Module } from '@nestjs/common';
import { ExampleController } from './example.controller';
import { LoggingInterceptor } from './logging.interceptor';
import { LoggingService } from './logging.service';
@Module({
controllers: [ExampleController],
providers: [LoggingService, LoggingInterceptor],
})
export class ExampleModule {}
通过以上步骤,可以确保拦截器能够正确地使用服务,并在方法调用前后执行自定义逻辑。
领取专属 10元无门槛券
手把手带您无忧上云