2016-07-15 73 views
1

我不明白爲什麼這段代碼可以很好的與angularjs 1.2.0-rc.2配合使用,但不適用於後續版本(我試過1.2.0,1.4.9,1.5.7)角度版本和承諾的問題

的index.html

<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> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script> 
    <!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>--> 
    <!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>--> 
    <!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>--> 
    <script src="scripts/app.js"></script> 
</body> 

腳本/ app.js

'use strict'; 

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

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

app.factory('GithubFactory', ['$q', '$http',function($q, $http) { 
    var myFactory = {}; 
    myFactory.getPullRequests = function() { 
     var deferred = $q.defer(); 
    $http.get('https://api.github.com/repos/angular/angular.js/pulls') 
      .success(function(data) { 
      deferred.resolve(data); // Success 
      }) 
      .error(function(reason) { 
      deferred.reject(reason); // Error 
      }); 

     return deferred.promise; 
    } 

    return myFactory; 

}]); 

調試,我可以看到的是,許是重解決,但數據不顯示... 什麼是正確的方式來使用承諾?

回答

2

它不起作用,因爲1.2版的承諾不會在模板中自動「展開」。您需要明確設置解決數據:

這是不正確的:

$scope.pullRequests = GithubService.getPullRequests(); 

而且應該是:

GithubService.getPullRequests().then(function(data) { 
    $scope.pullRequests = data; 
}); 

還有一件事。您不應該用deferred對象來承諾承諾,因爲$http服務已經爲您退貨:

app.factory('GithubFactory', ['$http', function($http) { 
    var myFactory = {}; 
    myFactory.getPullRequests = function() { 
     return $http.get('https://api.github.com/repos/angular/angular.js/pulls') 
      .then(function(response) { 
       return response.data; 
      }); 
    }; 
    return myFactory; 
}]); 
+0

是的! Promise自動解包已自1.2.0-rc.3棄用,請參閱https://docs.angularjs.org/guide/migration#angular-expression-parsing-parse-interpolate- – electblake