Amelia Grimaldi
Amelia Grimaldi

Reputation: 43

Angular js wait for data before return

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.

Upvotes: 4

Views: 2475

Answers (3)

Vivek
Vivek

Reputation: 1

Return your service inside the 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;
    });

Upvotes: 0

quirimmo
quirimmo

Reputation: 9998

You described perfectly what is happening. So my suggestion is to init the value of datas inside the service to an empty value (object, array, or whatever it will be after fetched the promise), associate the promise to the service, and simply move the promise resolution where you really need to manipulate that data. So inside 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 inject your service and do:

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

Upvotes: 3

Pritam Banerjee
Pritam Banerjee

Reputation: 18958

Whatever return you have you will have to put it inside the success method. Otherwise you will see that issue.

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

Upvotes: 1

Related Questions