0

I am using tsyringe as a dependency container and I have 2 classes. AccountingService and TransactionService. I am listening to the event triggered in TransactionService so that I can update the data in AccountingService using accountingRepository but on the method of updateTriggered, it shows an error Cannot read properties of undefined (reading 'findOne') on accountingRepository. Here is how my class look like:

AccountingService

@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 })
}
}

TransactionService:

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

console.log(this) in updateTrigger method is showing TransactionService object instead of AccountingService

Bellaraus
  • 3
  • 2
  • `accountingRepository ` is working fine. I want to understand why `console.log(this)` is showing `TransactionService` instead of `AccountingService` – Bellaraus May 18 '22 at 21:35

1 Answers1

0

Okay I found the solution. Changing it from

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

to:

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

solved it. So, what I understand is that, it will be the object of transactionService if we dont explicitly use .bind(this). Although, I am still waiting for the expert why is like this

Bellaraus
  • 3
  • 2