I have an angular service where I make an http post call. Also, some constant values are set there. In the end I use return to send these data to the controller, do some logic and display them in a view.
The service code:
var apiurl = 'myurl';
var apidata = {data: 'mydata'};
var myDataPromise = httppostrequest($http, apiurl, apidata);
myDataPromise.then(function(result) {
service.datas = result;
console.log("data.name"+result);
});
return service;
The httppostrequest function:
function httppostrequest($http, apiurl, apidata){
return $http({
method : "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: apiurl,
data: JSON.stringify(apidata),
timeout: 5000
});
}
The request is successful and returns the data. The problem is that the line
return service;
is executed before the data from the request are assigned to the service variable. Therefore the data from the post request are not even passed to the controller.
I have worked with node js, where there are ways and tools to avoid the asynchronous nature when needed. With angularjs I don't get it.