2015-01-21 85 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