最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2. Losing scope of this in Promise - Stack Overflow

programmeradmin0浏览0评论

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.

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 ponent. 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);
    }
}

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.

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 ponent. 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);
    }
}
Share Improve this question asked Aug 7, 2016 at 19:59 Andrew MacNaughtonAndrew MacNaughton 8132 gold badges7 silver badges21 bronze badges 1
  • Possible duplicate of How to access the correct `this` / context inside a callback? – Tamas Hegedus Commented Aug 7, 2016 at 20:07
Add a ment  | 

1 Answer 1

Reset to default 8

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.

You can use either the bind method:

ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
      .toPromise()
      .then(this.addToJobsTree.bind(this); // <-----
}

(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);
      });
}
发布评论

评论列表(0)

  1. 暂无评论