服务功能无法在 Angular 中访问“this”

时间:2021-05-06 13:21:15

标签: angular typescript

当我影响一个函数并调用它时,变量 this 未定义,因此 this.http.get... 出错 ERROR TypeError: Cannot read property 'http' of undefined

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

此外,当我在 const 中删除带有函数的逻辑并使用经典的 if else 进行调用时,它可以工作

if (this.isPastActivated) {
  this.facilityEvents$ = this.facilityService.getPastTimelineFacilities(0);
} else {
  this.facilityEvents$ = this.facilityService.getFutureTimelineFacilities(0);
}

1 个答案:

答案 0 :(得分:1)

当你将一个函数存储在一个变量中时,你必须以这种方式绑定它的所有者,否则它不记得它来自哪里:

const getFacilityEventsFunction = this.isPastActivated
      ? this.facilityService.getPastTimelineFacilities.bind(this.facilityService)
      : this.facilityService.getFutureTimelineFacilities.bind(this.facilityService);
    this.facilityEvents$ = getFacilityEventsFunction(this.iteration);
相关问题