I have an angular app but sometimes my callbacks seem to execute before they should. I have defined an service for my api calls, its methods look like this.
function addOffer(id) {
var request = $http({
method: "get",
url: "/api/campaign/offers",
params: {
action: "add",
id: id
}
});
return ( request.then(handleSuccess, handleError) );
}
function handleError(response) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (
!angular.isObject(response.data) || !response.data.message
) {
return ( $q.reject("An unknown error occurred.") );
}
// Otherwise, use expected error message.
return ( $q.reject(response.data.message) );
}
function handleSuccess(response) {
return ( response.data );
}
And then in my controller I have scope functions defined like this
$scope.addOffer = function(){
campaignService.addOffer($scope.id).then(
loadRemoteData()
);
};
The load remote data function syncs the client with what is stored in the application backend.
My problem is that in the controller method addOffer, the loadRemoteData() function fires before the offer is added, so that it loads the data without the new offer. But then upon a forced refresh that offer is there. Is there something that needs to be done differently so that this will work as expected?