'How to get response from one promise in two different methods in AngularJS
I need to do some changes to a legacy AngularJS application.
I have two methods in a controller:
const params: any = {id: 1};
public getGridData(): void {
this.dataService.getPanelData(params).then((response: any) => {
const dataToBeUsedInGrid = response.data.locationDetails;
// extra code
}
}
public getMapData() : void {
this.dataService.getPanelData(params).then((response: any) => {
const dataToBeUsedInMap = response.data.locationDetails.Coordinates;
// extra code
}
}
And this is the code in dataService which is just making an api call:
public getPanelData(params: any) {
return this.$http.post(this.dataConfigService.url, params);
}
Now this code is making two api calls. I just make to make one api call to server and use the response in different places as the response is same in both the calls. Both the getGridData and getMapData methods are called together asynchronously upon a record selection, and are responsible for displaying different data on the same page.
Solution 1:[1]
Conceptually a simple solution would be to refactor the code (functions) that call getGridData and getMapData into functions that are passed the data they need to update the page as an argument. Call the modified functions handleGridData and handleMapData for now.
Now refactor record selection to call getPanelData, then handleGridData, and then handleMapData in the asynchronous coding style of your choice. If you use async functions and the await operator you can probably in-line the code for the proposed handler functions, as well as handling errors gracefully.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | traktor |
