我创建了一个拦截器,如下所示,我希望在全局范围内使用它。我将拦截器添加到我的模块中并进行设置,以便 Nest js 应该根据NestJS Docs为我处理 DI ,但是当我向我的服务发出请求时,我收到一条错误消息,表明Cannot read property log of undefinedDI 似乎未被采用由 NestJS 照顾。
拦截器代码:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { LoggingService } from './logging.service';
@Injectable()
export class AuthInterceptor implements NestInterceptor {
constructor(private readonly loggingService: LoggingService) { }
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next
.handle()
.pipe(
map((response) => {
this.loggingService.log('Responded successfully');
return response;
})
);
}
}
Run Code Online (Sandbox Code Playgroud)
拦截模块:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';
@Module({
providers: [
LoggingService,
{
provide: APP_INTERCEPTOR,
useClass: AuthInterceptor,
},
],
})
export class AuthInterceptorModule {}
Run Code Online (Sandbox Code Playgroud)
我的app.module.ts应用程序的根目录导入了 AuthInterceptorModule。我假设我搞砸了一些事情,但我不清楚如何解决这个 DI 问题。
Ste*_*eve 10
在发现我的 LoggingService 依赖于请求范围内的另一个依赖项后,我能够自己解决这个问题。由于我的拦截器中存在请求范围的依赖项,这意味着我的拦截器也必须是请求范围的。
对代码的更改很简单,只需要我更改AuthInterceptorModule:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';
@Module({
providers: [
LoggingService,
{
provide: APP_INTERCEPTOR,
useClass: AuthInterceptor,
},
],
})
export class AuthInterceptorModule {}
Run Code Online (Sandbox Code Playgroud)
到
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR, Scope } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';
@Module({
providers: [
LoggingService,
{
provide: APP_INTERCEPTOR,
scope: Scope.REQUEST,
useClass: AuthInterceptor,
},
],
})
export class AuthInterceptorModule {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7839 次 |
| 最近记录: |