Within my Angular service, I am making an HTTP post call and setting some constant values. Once the data is retrieved, I use a return statement to send this data to the controller for further processing and display in a view.
Below is the code snippet of my service:
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 function used for the HTTP POST request:
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
});
}
Although the request is successful and returns the data, there is an issue with the line
return service;
being executed before the data from the request are assigned to the service variable. As a result, the data from the POST request does not get passed to the controller.
Having experience with Node.js, which provides ways to handle asynchronous operations, I find it challenging to manage this in AngularJS.