Flavio Oliveira Flavio Oliveira - 1 year ago 180
AngularJS Question

How to $http Synchronous call with AngularJS

sorry for my newbie question, but angularjs documentation is not very explicit or extensive as for someone figure basic stuff.

Is there some way to make a synchromous call with angularjs?


myService.getByID = function (id) {
var retval = null;

url: "/CO/api/products/" + id,
method: "GET"
}).success(function (data, status, headers, config) {

retval = data.Data;


return retval;

Answer Source

Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):

 xhr.open(method, url, true);

You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.

... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.

Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.

I hope that is helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download