当我影响一个函数并调用它时,变量 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);
}
答案 0 :(得分:1)
当你将一个函数存储在一个变量中时,你必须以这种方式绑定它的所有者,否则它不记得它来自哪里:
const getFacilityEventsFunction = this.isPastActivated
? this.facilityService.getPastTimelineFacilities.bind(this.facilityService)
: this.facilityService.getFutureTimelineFacilities.bind(this.facilityService);
this.facilityEvents$ = getFacilityEventsFunction(this.iteration);