gpt4 book ai didi

javascript - Angular 版本和 promise 的问题

转载 作者:行者123 更新时间:2023-11-30 15:56:48 25 4
gpt4 key购买 nike

我不明白为什么这段代码适用于 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>

scripts/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;

}]);

debugging 可以看到promise解决了,但是数据没有显示...使用 promise 的正确方法是什么?

最佳答案

它不起作用,因为 1.2 promises 不会在模板中自动“展开”。您需要明确设置已解析的数据:

这是不正确的:

$scope.pullRequests = GithubService.getPullRequests();

应该是:

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

还有一件事。你不应该用 deferred 对象构造 promise ,因为 $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;
}]);

关于javascript - Angular 版本和 promise 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38398237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com