pavelpie
9/25/2014 - 7:36 PM

$http, $q, and promise usage

//using services

//Method 1

//code inside controller:
$scope.wczytajListe = function(){
      daneBazy.podaj($scope.wyrob, $scope.seria).then(function(d){
         $scope.lista = d; 
      });  
}

//services code:

PotWyrobApp.factory('daneBazy', function($http){
  var Zapytania = {
       podaj : function(wyrob, seria){
       var dane = {'wyrob' : wyrob, 'seria' : seria};
       var wynik = {};
       var promise = $http({
                    method: 'POST',
                    url: "ajax/podajliste",
                    data: dane     
             }).then(function (response) {
                return response.data; 
             }, function(err) {
                alert("Błąd zapytania do serwera: " + err);
            });
        return promise;    
  }   
 return Zapytania;   
});

//METHOD 2 - using angular $q

//code inside the controller (here is for link function of directive)
var ladowanie_wyrobow = serwiswyrobow.podaj_wyroby();
                            ladowanie_wyrobow.then(function(dir_wyrob){
                                scope.dir_wyrob = dir_wyrob;
                                console.log(scope.dir_wyrob);
                            }, function(status){
                               alert ("błąd załadowania poprawnego strony"); 
                            });
//service code:

.factory('serwiswyrobow', function($http, $q){
                var funkcje = {
                    podaj_wyroby: function(){
                        var deffered = $q.defer();
                        $http({
                            method: 'GET',
                            url: BASE+'/serwis/wyroby/all'
                        })
                        .success(function(data, status, headers, config){
                            deffered.resolve(data);
                        })
                        .error(function(data, status, headers, config){
                            deffered.reject(status);
                        });
                        
                        return deffered.promise;
                    }
                }
                return funkcje;
            })

//I wanted to visualise this for myself, I don't get it but I feel no sense using $q objects.