-3

When I affect a function and call it, the variable this is undefine, so the this.http.get... is in error ERROR TypeError: Cannot read property 'http' of undefined

const getFacilityEventsFunction = this.isPastActivated
      ? this.facilityService.getPastTimelineFacilities
      : this.facilityService.getFutureTimelineFacilities;
    this.facilityEvents$ = getFacilityEventsFunction(this.iteration);

Also, when I remove the logic with the function in a const and do a call with a classic if else, it works

if (this.isPastActivated) {
  this.facilityEvents$ = this.facilityService.getPastTimelineFacilities(0);
} else {
  this.facilityEvents$ = this.facilityService.getFutureTimelineFacilities(0);
}
Leyff da
  • 206
  • 3
  • 13

1 Answers1

1

When you store a function in a variable, you have to bind the owner of it this way, otherwise it doesn't remember where it comes from:

const getFacilityEventsFunction = this.isPastActivated
      ? this.facilityService.getPastTimelineFacilities.bind(this.facilityService)
      : this.facilityService.getFutureTimelineFacilities.bind(this.facilityService);
    this.facilityEvents$ = getFacilityEventsFunction(this.iteration);
Random
  • 2,547
  • 1
  • 10
  • 22
  • The less repetitive option would probably be `getFacilityEventsFunction.call(this.facilityService, this.iteration)`… – deceze May 06 '21 at 13:28
  • Your code works, but I dont fint it pretty to handle the injection so I came back to the if else. If you think the bind is better don't hesitate to teach me why tho. Thanks :) – Leyff da May 06 '21 at 13:49