3

I want custom sync and async in angularjs like below.

  var async = function (url, data, action, callback) {   
        $.ajax({
            url: global.baseURL + url,
            type: action,
            data: data,                
            async: true,//or false
            success: function (data) {
                if (data !== undefined && data !== null) {
                    callback(data);
                }
            }
        });
    }; 

In AngularJs look like this code

 $http({ method: 'GET', url: baseURL + 'Api/MobilePref/Get/'+uid
        })
        .success(function (data, status, headers, config) {
        })
        .error(function (data, status, headers, config) {
            //TODO: handl error.
        });

Can any one tell me how to setup sync and async call in angularjs?

Anil Singh
  • 4,173
  • 4
  • 41
  • 47
  • Seems like it is not possible. [AngularJs: $http Synchronous call](http://stackoverflow.com/questions/26603532/angularjs-http-synchronous-call) – halafi Jan 21 '15 at 11:41
  • Synchronous calls are not possible in the $http. The backend sets async by default. Synchronous calls cause blocking and blocking is bad! – haxtbh Jan 21 '15 at 11:44
  • can any one give an idea to resolve it? – Anil Singh Jan 21 '15 at 11:56

1 Answers1

2

You can do this:

function callAjax(url, callback){
    var xmlhttp;

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true); // the flag true tell if this is async or not and then you can call $scope.$apply for angular to know.
    xmlhttp.send();
}
Bazinga
  • 10,716
  • 6
  • 38
  • 63