1

When I get an array of objects with httpClient, I can access properties of each object in the array, but I cannot access methods. I don't understand why, and how can I do this.

this.interventionService.getInterventions().subscribe(interventions =>
        { 
            interventions.forEach(it => {

               console.log(it.InterventionId); // property can be accessed
               console.log(it.myMethod()); // myMethod cannnot be accessed

               // I get an error: 'myMethod is not a function'

            });
        });

However, if I create a new object, I can access the methods:

var it = new Intervention();
it.myMethod(); // no error

Thanks for help

bruno
  • 91
  • 3

1 Answers1

0

You need to set the correct this context for the method using bind.

this.interventionService.getInterventions().subscribe(interventions => {
  interventions.forEach(it => {
      it.myMethod.bind(it)();
  });
});
Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79