我觉得我在这里错过了一些东西。我有一项可以获取一些数据的服务。我将其转换为承诺,然后尝试以单独的方法处理数据。
一旦它命中该方法,我就失去了访问我通常从 this.whatever 访问的对象的能力。如果我将 addJobsToTree 中的所有代码保留在 then 块中,则它可以正常工作。我还可以从组件中的任何其他位置访问它。我确信我在做一些愚蠢的事情,但无法弄清楚。
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
method:
ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
.toPromise()
.then(this.addToJobsTree.bind(this); // <-----
}
(note:这是使用的缺点bind
使用 TypeScript 的方法:https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html)
或箭头函数来解决这个问题:
ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
.toPromise()
.then((data) => { // <-----
this.addToJobsTree(data);
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)