xenurs
xenurs

Reputation: 449

Return value of $q promise

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

Hi, I'm new in AngularJS, and I want to know how can I send data I received from API into a global variable and inject it into a $scope. In this example, I want to send my result from $q and show it in my view.

Upvotes: 1

Views: 377

Answers (1)

Eigi
Eigi

Reputation: 716

Do it like this:

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

You should also implement the error of the http response like:

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

Your code in the success-callback is not the best one. Basicly it does work, but you will have some timing issues (and it does not make much sense).

Upvotes: 1

Related Questions