UnderWood UnderWood - 5 months ago 230
Javascript Question

Angular2: Calling other functions inside call back functions

I am building an Angular2 application.
I have an asynchronous function

deleteObject
in
myService
. It returns a Promise. I have another function in the Component called
refresh
, which refreshes the page. How do I call refresh from inside the Promise. This is what I tried:

export class AppComponent{

refresh(){
// refresh page here
}

delete(){
this.myService.deleteObject(params).then(
function(data){
//this.refresh() doesn't work here.
});
}
}

Answer

this is a context issue. "this" refers to the callback function's context, which could be the promise or something. what you actually want is a reference to the component context, you can achieve that like so

delete(){
    var componentRef = this; // colloquially "that" or "self"
    this.myService.deleteObject(params).then(
       function(data){
         componentRef.refresh() // does work here.
    });
}