我觉得我在这里遗漏了一些东西。我有一项服务可以获取一些数据。我将其转换为 promise ,然后尝试以单独的方法处理数据。
一旦它命中方法,我就失去了访问我通常从 this.whatever 访问的对象的能力。如果我将 addJobsToTree 中的所有代码留在 then block 中,它就可以正常工作。我还可以从组件中的任何其他地方访问它。我确定我正在做一些愚蠢的事情,但无法弄清楚。
ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
.toPromise()
.then(this.addToJobsTree);
}
private addToJobsTree(res){
for(let xx of res){
this._sharedService.jobs.push(xx); //Comes back as cannot read _sharedService of null
console.log(this._sharedService.jobs);
}
}
最佳答案
这是因为你引用了一个函数而你失去了函数的上下文。要解决此问题,您需要将函数显式链接到对象。
您可以使用 bind
方法:
ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
.toPromise()
.then(this.addToJobsTree.bind(this); // <-----
}
(注意:这是在 TypeScript 中使用 bind
方法的缺点:https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html )
或者一个箭头函数来解决这个问题:
ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
.toPromise()
.then((data) => { // <-----
this.addToJobsTree(data);
});
}
关于javascript - Angular 2. 在 Promise 中丢失 this 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38818006/