UnderWood
UnderWood

Reputation: 883

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

Upvotes: 0

Views: 4689

Answers (2)

BeetleJuice
BeetleJuice

Reputation: 40886

If you are coding in Typescript, you can use fat arrow functions instead. They keep the this context you would expect. So replace

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

With this:

delete(){
    this.myService.deleteObject(params).then(
            (data)=>{
                //this.refresh() should work here
            }
    );
}

Upvotes: 8

kirinthos
kirinthos

Reputation: 452

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

Upvotes: 1

Related Questions