Search code examples
angulartypescriptangular2-services

angular 2+ refresh callback not working as expected


i have one issue with angular 2+ and typescript, i have 2 components and one service, what i need to achieve is when i open Modal(component) and do one action (in my case i do http.post) so when i click Add button inside modal i need to run another function in other component. To achieve that i created "refresh callback" function.

So in shared service i have this

private refreshCallback = Function;

setRefreshCallback(callback) {
  refreshCallback = callback;
}

runRefreshCallback() {
  refreshCallback();
}

And inside my component where i need to do refresh when user clicks Add in modal i have this

getSomeData() {
 this.service.getData().toPromise().then(data=>{
   // do some stuff
});
}

and on ng init i just set callback that i need to run when modal action button is clicked

ngOnInit() {
   this.service.setRefreshCallback(this.getSomeData);
}

next thing inside modal i just run refreshCallback each time when user clicks Add Button like this

add() {
// do some stuff 
this.service.runRefreshCallback();
}

What happens here is callback works normally it actually enters inside getSomeData function in other component like i expected, BUT i get error this.service.getData() is undefined bla bla bla..., so i don't understand why callback function does not see this.service in its own component, it works on ngInit it loads all data and do stuff that is needed, but its undefined when refresh callback is started ?


Solution

  • Your context this inside getSomeData function gets lost when you pass it like below:

    ngOnInit() {
       this.service.setRefreshCallback(this.getSomeData);
    }
    

    To fix this wrap the place where you pass this function inside an arrow function:

    ngOnInit() {
       this.service.setRefreshCallback(() => this.getSomeData());
    }
    

    See red flags for this in the TypeScript documentation.