简体   繁体   English

Nestjs,在拦截器中使用依赖注入类的方法时遇到一些问题,注入无法解决

[英]Nestjs, met some problems when using dependency injected class's method in interceptors, inject can't be resolved

I injected a provider(FileFilter) in my controller, and I want to use its filter method in Interceptors.我在控制器中注入了一个 provider(FileFilter),我想在拦截器中使用它的过滤器方法。

@Controller('file-uploader')
export class FileUploaderController {

    constructor(private fileFilter: FileFilter) {}

    @Post()
    @UseInterceptors(
        FileInterceptor('file', {
            fileFilter: this.fileFilter.filter,
        }))

    uploadFile(@UploadedFile() file) {
        return file;
    }
}

here is FileFilter这是文件过滤器


@Injectable()
export class FileFilter {
    filter(req: any, file: MulterFile, callback: any) {
        if (!file.mimetype.match(ASSESSMENT_FILE_TYPE)) {
            return callback(new HttpException(null, HttpStatus.BAD_REQUEST), false);
        }
        return callback(null, true);
    }

}

when I use postman to request the API, the error message is like the following:当我使用 postman 请求 API 时,错误消息如下所示:

fileFilter: this.fileFilter.filter,
[0]                          ^
[0] TypeError: Cannot read property 'filter' of undefined

BUT inside the post method, the filter can be used which means the FileFilter is injected correctly, then who can explain why this doesn't work in an interceptor?但是在 post 方法中,可以使用过滤器,这意味着 FileFilter 被正确注入,那么谁能解释为什么这在拦截器中不起作用? or is this about the init order or something?或者这是关于 init 命令还是什么? Help, please.请帮忙。

Decorators have a different Lexical this which does not belong to the class, so this.fileFilter.filter is undefined as this does not have a property called fileFilter .装饰器有一个不同的词法this ,它不属于类,所以this.fileFilter.filter是未定义的,因为this没有名为fileFilter的属性。 I believe you would need to save the filter method as a function and not part of a class to use it like that我相信您需要将filter方法保存为函数而不是类的一部分才能像那样使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM