2015-01-21 143 views
2

我想在下面的angularjs中进行自定义同步和异步。如何在angularjs中调用同步和异步?

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

在AngularJs看起来像这样的代码

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

任何一个可以告诉我如何设置同步和异步调用的angularjs?

+0

看起来这是不可能的。 [AngularJs:$ http Synchronous call](http://stackoverflow.com/questions/26603532/angularjs-http-synchronous-call) – halafi 2015-01-21 11:41:56

+0

同步调用在$ http中是不可能的。后端默认设置为异步。同步呼叫导致阻塞和阻塞不好! – haxtbh 2015-01-21 11:44:19

+0

任何人都可以给出一个想法来解决它? – 2015-01-21 11:56:14

回答

1

你可以这样做:

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(); 
} 
+2

xmlhttp.open(“GET”,url,false); //这意味着我们可以说这是一个“同步”呼叫? – 2015-01-21 14:45:21

+1

不,设置为true是同步呼叫 – Bazinga 2015-01-22 08:47:59