Angular 2. 在 Promise 中失去 this 的范围 [英] Angular 2. Losing scope of this in Promise
问题描述
我觉得我在这里遗漏了一些东西.我有一个服务可以获取一些数据.我将其转换为承诺,然后尝试以单独的方法处理数据.
I feel like I am missing something here. I have a service that grabs some data. I convert it to a promise and then try and work on the data in a seperate method.
当它遇到方法时,我失去了访问我通常从 this.whatever 访问的对象的能力.如果我将 addJobsToTree 中的所有代码保留在 then 块中,它就可以正常工作.我也可以从组件中的其他任何地方访问它.我确定我在做一些愚蠢但无法弄清楚的事情.
When once it hits the method I loose the ability to access my objects that i would normally access from this.whatever. If I leave all the code from the addJobsToTree in the then block, it works fine. I can also access this from every where else in the component. I'm sure i'm doing something dumb but can't figure it out.
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);
}
}
推荐答案
这是因为您引用了一个函数,而您丢失了该函数的上下文.要解决这个问题,您需要将函数显式链接到一个对象.
It's because you reference a function and you lose the context of the function. To fix that you need to explicitly link the function to an object.
您可以使用 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)
(note: here is the drawback to using the bind
method with TypeScript: https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html)
或者一个箭头函数来解决这个问题:
or an arrow function to fix that:
ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
.toPromise()
.then((data) => { // <-----
this.addToJobsTree(data);
});
}
这篇关于Angular 2. 在 Promise 中失去 this 的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!