Reputation: 883
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
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
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