【问题标题】:Argument of type 'typeof globalThis' is not assignable to parameter of type 'EntryService'“typeof globalThis”类型的参数不能分配给“EntryService”类型的参数
【发布时间】: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 并没有通过依赖注入器将所有这些依赖注入到服务中。

我尝试了不同的方法,但无济于事。好像我不完全明白发生了什么。

有什么想法吗?

那么构建代码的正确方法是什么?

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

    问题出在下面一行:

    @RecordEntryOperation(new CreateOperation(this))
    

    this 并不像您预期​​的那样引用EntryService 的实例,而是引用globalThisthis 实际上是指当前模块),因此出现错误。您可以做的是稍微更改您的 Operation-class 并将 entryService 传递给 execute 方法。

    export class CreateOperation extends Operation {
        constructor() { super(); }
    
        public async execute(entryService: EntryService): Promise<any> {
            return entryService.someEntryServiceOperation();
        }
    }
    

    然后你可以在你的装饰器中做以下事情:

    export const RecordEntryOperation = (OperationType: typeof CreateOperation) => {
        return (target: object, key: string | symbol, descriptor: PropertyDescriptor) => {      
            const operation = new OperationType(); 
            const original = descriptor.value;
            descriptor.value = async function(...args: any[]) {
                const response = await original.apply(this, args);
                console.log(`operation.execute()`, await operation.execute(this));
                return response;
            };
        };
    };
    

    然后使用它:

    @RecordEntryOperation(CreateOperation)
    public async create(createEntryDto: CreateEntryBodyDto): Promise<Entry> { .. }
    

    【讨论】:

    • 有一个小错误,请重新加载并获取最新版本:)
    • 尝试运行这段代码,一切看起来都很顺利,但由于某种原因,RecordEntryOperation 中的this.entryServiceundefined
    • 哦,它实际上应该只是this,因为this EntryService,对吧?查看我的编辑。
    • 啊,是的,对,我没有注意到它,现在它似乎按预期工作了!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多