0

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.
        });
    }
}    
UnderWood
  • 803
  • 3
  • 12
  • 23

2 Answers2

8

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
            }
    );
}
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
1

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.
    });
}
kirinthos
  • 452
  • 2
  • 9
  • also fwiw, you could look into [rxjs observables](http://blog.angular-university.io/functional-reactive-programming-for-angular-2-developers-rxjs-and-observables/) which is a powerful angular paradigm (technically rxjs paradigm, but they incorporate it) – kirinthos Jun 20 '16 at 22:54
  • Thanks @kirinthos. I am new to Javascript. It worked for me. :) – UnderWood Jun 20 '16 at 22:54
  • @UnderWood might i suggest giving [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) a read – kirinthos Jun 20 '16 at 22:55
  • Thank @kirinthos. I will take a look at it. – UnderWood Jun 20 '16 at 23:03