Andrew MacNaughton
Andrew MacNaughton

Reputation: 813

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.

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

Upvotes: 2

Views: 2812

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202326

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

Upvotes: 8

Related Questions