AngularJS: uso delle promise con AJAX

In AngularJS un tipico esempio dell'uso delle promise riguarda le richieste AJAX.

AngularJS di Gabriele Romanato

In AngularJS un tipico esempio dell'uso delle promise riguarda le richieste AJAX.

Possiamo creare una promise e risolverla o rigettarla in base all'esito della richiesta AJAX: in caso di successo la promise verrĂ  risolta e in caso di errore verrĂ  rigettata.


var app = angular.module('MyApp', []);

app.factory('GithubService', ['$q', '$http',function($q, $http) {
          var getPullRequests = function() {
            var deferred = $q.defer();
            
            $http.get('https://api.github.com/repos/angular/angular.js/pulls')
            .success(function(data) {
              deferred.resolve(data); // Successo: risolvo la promise
            })
            .error(function(reason) {
              deferred.reject(reason); // Errore: rigetto la promise
            });
            
            return deferred.promise; // Restituisco una promise
          }

          return {
            getPullRequests: getPullRequests
          };
}]);

app..controller('DashboardCtrl', ['$scope', 'GithubService',function($scope, GithubService) {
    $scope.pullRequests = GithubService.getPullRequests();
}]);

La nostra view:


<body ng-app="MyApp">
	<h1>Open Pull Requests for Angular JS</h1>

  <ul ng-controller="DashboardCtrl">
    <li ng-repeat="pullRequest in pullRequests">
      {{ pullRequest.title }}
    </li>
  </ul>
</body>