【发布时间】:2013-08-21 01:09:05
【问题描述】:
我正在做一些小练习来学习 AngularJS,目前试图了解如何使用 Promise。
在下面的练习中,我试图让一些数据异步。我可以在 console.log 中看到数据,但是 promise 返回 NULL。
- GET /entries 200 OK
- 承诺已解决:null
任何有经验的人都可以给我一些建议,以了解我做错了什么?感谢收看!
angular.module('questions', [])
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
resolve: {
'MyServiceData': function(EntriesService) {
return EntriesService.promise;
}
}
})
})
.service('EntriesService', function($http) {
var entries = null;
var promise = $http.get('entries').success(function (data) {
entries = data;
});
return {
promise: promise,
all: function() {
return entries;
}
};
})
.controller('MainCtrl', ['$scope', 'EntriesService', function($scope, EntriesService) {
console.log('Promise is resolved: ' + EntriesService.all());
$scope.title = "Q&A Module";
$scope.entries = EntriesService.all() || [];
$scope.addMessage = function() {
$scope.entries.push({
author: "myAuthor",
message: $scope.message
});
};
}]);
/******感谢大家迄今为止的帮助** ***/
在听取了@bibs 的建议后,我想出了以下解决方案,使用 ngResource 很清楚:
angular.module('questions', ['ngResource'])
.factory('EntriesService', function($resource){
return $resource('/entries', {});
})
.controller('MainCtrl', ['$scope', 'EntriesService', function($scope, EntriesService) {
$scope.title = "Q&A Module";
$scope.entries = [];
EntriesService.query(function(response){
$scope.entries = response;
});
$scope.addMessage = function() {
$scope.entries.push({
author: "myAuthor",
message: $scope.message
});
};
}]);
【问题讨论】:
-
你想达到什么目的?在您登录
EntriesService.all()时,您的承诺似乎尚未解决,因此该值仍然为空。 -
坦克寻找@bibs!我想在调用 mainCtrl 的任何时候异步获取一些数据,所以在这种情况下,我想知道“EntriesService”如何在我 console.log() 时获得可用的数据!我还在学习,所以我认为,通过创建“服务”并使用 promise 这将返回数据。很明显,我并没有完全理解 Promise,因此,当我初始化它时,数据在 ctrl 中不可用。应该怎么写正确?
标签: javascript angularjs promise