2014-03-13 66 views
0

大家好我是新的角js,在這裏我想從服務器獲取json到控制器,以便我可以處理數據,但是這裏發生的是第一個警報-11被稱爲然後警報2被調用,在被調用結束提示1,我讀到的承諾,所以我嘗試過,但仍然沒有工作,我希望它發生了一個又一個,請幫我.Thanks提前異步調用角js

sampleApp.controller('firstpage', function ($scope, $q, $http, $templateCache, onlinedata, offlinedata) { 
    $scope.message = 'This is Add new order screen'; 
    var defer = $q.defer(); 
    defer.promise.then(function() { 
     $scope.method = 'POST'; 
     $scope.url = 'http://ncrts.com/ncrtssales_compadmin/webservices/user_login'; 
     $scope.fetch = function() { 
      $scope.code = null; 
      $scope.response = null; 
      alert($scope.response + 11) //alert11 
      $http({ 
       method: $scope.method, 
       url: $scope.url, 
       cache: $templateCache 
      }). 
      success(function (data, status) { 
       $scope.status = status; 
       $scope.message = data; 
       alert($scope.message + 1) //alert1 
      }). 
      error(function (data, status) { 
       $scope.data = data || "Request failed"; 
       $scope.status = status; 
      }); 
     }; 
     $scope.fetch(); 
    }) 
     .then(function() { 
     alert($scope.message + 2); //alert 2 
    }) 
    defer.resolve(); 
    //alert($scope.remember) 
}); 
+0

警報3在哪裏? –

+0

對不起警報1,編輯它 – kavinhuh

回答

4

您必須使用解析函數和拒絕函數來處理答覆。您可以在AngularJS documentation中找到有關承諾的更多信息。我在代碼中做了一些改動,告訴你如何實現你想要的。

sampleApp.controller('firstpage', function ($scope, $q, $http, $templateCache, onlinedata, offlinedata) { 
$scope.message = 'This is Add new order screen'; 
var defer = $q.defer(); 

    $scope.method = 'POST'; 
    $scope.url = 'http://ncrts.com/ncrtssales_compadmin/webservices/user_login'; 

    $scope.fetch = function() { 
     $scope.code = null; 
     $scope.response = null; 
     alert($scope.response + 11) //alert11 

     var defer = $q.defer(); 
     $http({ 
      method: $scope.method, 
      url: $scope.url, 
      cache: $templateCache 
     }). 
     success(function (data, status) { 
      //$scope.status = status; 
      $scope.message = data; 
      alert($scope.message + 1) //alert1 
      defer.resolve({ 
       status: status, 
       message: data 
      });     
     }). 
     error(function (data, status) { 
      var data = data || "Request failed"; 
      //$scope.status = status; 
      defer.reject({ 
       status: status, 
       message: data 
      });        
     }); 
     return defer.promise; 
    }; 

    $scope.fetch().then(function (data) { 
     alert('Status: ' + data.status); 
     alert('Message: ' + data.message);    
    }); 
}); 
3

我我的代碼格式非常混亂。它可以幫助您在服務中編寫異步調用,然後將服務注入到控制器中。請記住,以下是我在AngularJS中就異步調用和承諾瞭解到的一些一般建議:

  • 您的服務最初應返回延期承諾。然後這個承諾 應該在異步調用的success()上解決。
  • $http()退貨之後,但在success()退貨之前,您有一個 未解決的承諾。如果您有要運行後 承諾解決的代碼,你需要使用then()來表明您 要在then()塊中執行的代碼,一旦你 接收到的數據(和解決的承諾) 。
  • 未使用then()此 情況將導致錯誤,因爲您將嘗試訪問 尚未存在的數據。

從你的代碼看來,你已經意識到了你所需要的編碼策略,但它總是有助於將異步調用隔離到服務中,這樣框架可以讓你的生活更輕鬆。祝你好運。

+1

其實我想保持ajax調用服務,但要張貼在這裏我混了起來,謝謝你爲我們的指導方針非常有用謝謝你 – kavinhuh