Currently, I have a service that is responsible for updating a value on the database.
My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request used by the service, the return value is not immediately available and ends up being undefined in the controller.
If I were to make the HTTP request inside the controller, I would simply update the scope within the callback function. But, because I am using a service, the scope's accessibility is limited.
I believe returning a Promise might be the solution to address this issue, but I am curious if there is a simpler alternative.
SERVICE
.service('doStuff',function($http){
this.update = function(data) {
$http.post('http://api.internet', data).then(function(res){
return(res.data.result);
});
}
})
CONTROLLER
/* Once service is injected into controller */
var result = doStuff.update(data);
console.log(result); // Returns undefined as expected
I initially assumed that by returning from the HTTP callback, it would wait for the result to be available before completing, but it appears that I may have overlooked something essential.