0

This is what I am trying to do, I pass a function reference from Provider1 (present in module1) to Provider2 (present in module2). When I try to invoke the function, the value of "this" is undefined. Any idea on what might have gone wrong?

Module1.ts

@Module({
  controllers: [Controller1],
  providers: [Provider1],
})
export class Module1{}

Provider1.ts

@Injectable()
export class Provider1 {
  constructor(private readonly provider2: Provider2) {} 
  providerFunction() {
    this.provider2.provider2Function(new HelperClass().helperFunction);
  }
}

HelperClass.ts

@Injectable()
export class HelperClass {
  helperFunction() {
    return this.someValue; //Here, this is undefined
  }
}

Provider2.ts

@Injectable()
export class Provider2 {
  provider2Function(helperFunction: ()=>void) {
    console.log(helperFunction());
  }
}

1 Answers1

0

It's because this gets changed when the method is passed that way. Try like this:

@Injectable()
export class Provider1 {
  constructor(private readonly provider2: Provider2) {} 
  providerFunction() {
    const helper = new HelperClass();
    this.provider2.provider2Function(helper.helperFunction.bind(helper));
  }
}

More on how does the this keyword work here.

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38