我是 Nest.js 的新手,想要为我的自定义类实现“基于属性的注入”。
# author.module.ts
import { Module } from '@nestjs/common';
import { AuthorService } from './author.service';
import { AuthorController } from './author.controller';
import { ConfigModule } from '@nestjs/config';
import { ConfigurationHelper } from 'src/tools/helpers/configuration-helper';
@Module({
imports: [ConfigModule],
controllers: [AuthorController],
providers: [AuthorService, ConfigurationHelper],
})
export class AuthorModule {}
# author.controller.ts
...
constructor(private readonly authorService: AuthorService) {}
@Get()
findAll() {
return this.authorService.findAll();
}
...
# author.service.ts
import { Injectable } from '@nestjs/common';
import { CustomException } from 'src/tools/helpers/custom-exceptions';
@Injectable()
export class AuthorService {
constructor() {}
findAll() {
new CustomException('some message');
return `This action returns all author`;
}
}
# src/tools/helpers/custom-exceptions.ts
import { Inject } from '@nestjs/common';
import { ConfigurationHelper } from './configuration-helper';
export class CustomException {
@Inject()
private readonly configurationHelper: ConfigurationHelper;
constructor(myMsg: string) {
const message = myMsg + this.configurationHelper.getEnv();
}
}
# src/tools/helpers/configuration-helper.ts
import { ConfigService } from '@nestjs/config';
import { Injectable } from '@nestjs/common';
@Injectable()
export class ConfigurationHelper {
constructor(private readonly configService: ConfigService) {}
getEnv(): string {
return this.configService.get<string>('ENV');
}
}
但是当我调用端点时,抛出了这个错误: 错误 [ExceptionsHandler] 无法读取未定义的属性(读取“getEnv”) 对于 this.configurationHelper。看起来“ConfigurationHelper”没有被注入。
我是根据文档做的这里
我做错了什么?
如果你拨打
new
,你就100%负责课堂上的一切。 Nest将为您做无注射
如果 Nest 为您创建了类,则您不能在构造函数内使用基于属性的注入属性,因为构造函数必须先完成运行,然后 Nest 才能将任何类属性分配给实例