Angular js waits for data before returning

I have an angular service where I make a http post call. In addition, some constant values ​​are set there. At the end, I use return to send this data to the controller, do some logic, and display it in the view.

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;

      

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 was successful and returns data. The problem is that the line

return service

is executed before the data from the request is assigned to the service variable. Therefore, the data from the post request is not even transmitted to the controller.

I've worked with node js where there are ways and tools to avoid the asynchronous nature when needed. With angularjs I don't understand.

+3


source to share


3 answers


You have described perfectly what is happening. So my suggestion is to initialize the value datas

inside the service to an empty value (object, array, or whatever happens after receiving the promise), bind the promise to the service, and just move the promise solution where you really need to manipulate that data. Therefore, in your service:

var apiurl = 'myurl';
var apidata = {data: 'mydata'};
service.datas = []; // if it will be an array for example
service.myDataPromise = httppostrequest($http, apiurl, apidata);

return service;

      



And then wherever you need it, just enter your service and do:

myService.myDataPromise.then(function(result) {
  myService.datas = result;
  console.log("data.name"+result);
});

      

+2


source


Whatever you have, you have to put it in the success method. Otherwise, you will see this problem.

You can do something like this:



 var data = {} //your data
 var promiseURLMetaData = HttpService.httpPost("parseUrlMetadata", data);
 promiseURLMetaData.then(function (response) {
     var urlMetaData = response.data;
     return urlMetaData;
  })
 .catch(function (error) {
    console.log("Something went terribly wrong while trying to get URL Meta Data.");
 });

      

+1


source


Return your service inside a result function.

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;
    });

      

0


source







All Articles