$ q promise的返回值

时间:2016-02-26 10:34:04

标签: angularjs angularjs-scope

//controller pour connection to API
.controller('LoginConnect', ['$scope', 'connecting',
function($scope,connecting){
    $scope.user = {};
    var users = $scope.user;


    $scope.connect = function (users) {

      var log = $scope.user.login;
      var pass = $scope.user.password;
      var mydata = {};
      connecting.login(log,pass,mydata);
      $scope.datab = mydata;
    };
  }
])

  //factory pour aller chercher le token
.factory('connecting', ['$http','$q', function ($http,$q){
      var token;
      var ConnectingFactory = {};
      ConnectingFactory.login = function(log,pass){

       var deferred = $q.defer();
       $http({
           method: 'POST',
           url: "http://api.tiime-ae.fr/0.1/request/login.php",
           headers: {'Content-Type': 'application/x-www-form-urlencoded'},
           transformRequest: function(obj) {
               var str = [];
               for(var p in obj)
               str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
               return str.join("&");
           },
           data: {login: log, password: pass}
           })
       .success(function(result){
          deferred.resolve(result);
          var promise = deferred.promise;
          promise.then(function(result){
          var  mydata = result["data"];
            }
          );
         })
       };
       return ConnectingFactory;
}]);
;

嗨,我是AngularJS的新手,我想知道如何将从API收到的数据发送到全局变量并将其注入$ scope。在这个例子中,我想从$ q发送我的结果并在我的视图中显示它。

1 个答案:

答案 0 :(得分:1)

这样做:

ConnectingFactory.login = function(log,pass){
   var deferred = $q.defer();
       $http({...}).success(function(data){
           deferred.resolve(data);
       });

  return deferred.promise;
}

connecting.login(log,pass).then(function(data){
   $scope.datab = data; // your recived data
});

您还应该实现http响应的错误,如:

.error(function(data){
   deffered.reject(data);
});

成功回调中的代码并不是最好的。基本上它确实有效,但你会遇到一些时间问题(并没有多大意义)。