【发布时间】:2020-11-03 03:27:05
【问题描述】:
我正在尝试将我的服务传递给我传递给方法装饰器的类的实例。
这里是服务:
@Injectable()
export class EntryService {
constructor(
@InjectRepository(EntryEntity)
private readonly entryRepository: Repository<EntryEntity>,
@InjectRepository(ImageEntity)
private readonly imageRepository: Repository<ImageEntity>,
private readonly awsService: AwsService,
private readonly connection: Connection,
private readonly categoriesService: CategoriesService,
private readonly cacheService: CacheService,
private readonly usersService: UserService,
private readonly imagesService: ImagesService,
private readonly notificationService: NotificationsService,
) {}
@RecordEntryOperation(new CreateOperation(this))
public async create(createEntryDto: CreateEntryBodyDto): Promise<Entry> {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
await queryRunner.commitTransaction();
// more code
} catch (err) {
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
}
}
这里的事情是我需要在传递给RecordEntryOperation 装饰器的那个类中使用EntryService。
装饰器(尚未完全实现):
export const RecordEntryOperation = (operation: Operation) => {
return (target: object, key: string | symbol, descriptor: PropertyDescriptor) => {
const original = descriptor.value;
descriptor.value = async function(...args: any[]) {
const response = await original.apply(this, args);
console.log(`operation.execute()`, await operation.execute());
return response;
};
};
};
CreateOperation 类如下所示(尚未完全实现):
export class CreateOperation extends Operation {
constructor(public entryService: EntryService) { super(); }
public async execute(): Promise<any> {
return this.entryService.someEntryServiceOperation();
}
}
我得到的错误如下:
Argument of type 'typeof globalThis' is not assignable to parameter of type 'EntryService'.
Type 'typeof globalThis' is missing the following properties from type 'EntryService': entryRepository, imageRepository, awsService, and 53 more.
我不完全理解这个错误是关于什么的。我怀疑这意味着传递给CreateOperation 类的this 并没有通过依赖注入器将所有这些依赖注入到服务中。
我尝试了不同的方法,但无济于事。好像我不完全明白发生了什么。
有什么想法吗?
那么构建代码的正确方法是什么?
【问题讨论】: