2014-03-13 67 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