typescript - Nodejs / Typescript:在多个类之间使用 EventEmitter

我使用 tsyringe 作为依赖容器,我有 2 个类。 AccountingServiceTransactionService。我正在监听 TransactionService 中触发的事件,以便我可以使用 accountingRepository 更新 AccountingService 中的数据,但在 updateTriggered 方法上,它在 accountingRepository 上显示错误 Cannot read properties of undefined (reading 'findOne')。这是我的Class的样子:

会计服务

@injectable()
class AccountingService {
 constructor(
   private accountingRepository: AccountingRepository,
   private transactionService: TransactionService
 ) {
    this.transactionService.on('updateTrigger', this.updateTrigger);
}

private async updateTrigger(data: any) {
   this.accountingRepository.findOne({ id: data.id })
}
}

交易服务:

@injectable()
    class TransactionService extends EventEmitter {
     constructor(
       ...Some dependencies,
     ) {}
    
    private async someTransactionOccurred(data: any) {
       this.emit('updateTrigger', 'id', {});
    }
    }

updateTrigger 方法中的 console.log(this) 显示 TransactionService 对象而不是 AccountingService

回答1

好的,我找到了解决方案。改变它从

this.transactionService.on('updateTrigger', this.updateTrigger);

至:

this.transactionService.on('updateTrigger', this.updateTrigger.bind(this));

解决了。所以,我的理解是,如果我们不显式使用 .bind(this),它将是 transactionService 的对象。虽然,我还在等专家为什么会这样

相似文章

随机推荐

最新文章