我正在尝试使用ngRoute的promise。我已经阅读了关于决心的内容,但我无法使其成功。模板只是获取消息数组的promise对象。这就是它的样子:
angular.module('myModule', ['ngRoute'])
.factory('MessageResolver', ['$q', '$timeout', function($q, $timeout)
{
var x = function()
{
var deferred = $q.defer();
$timeout(function()
{
deferred.resolve(['Hello', 'world!']);
}, 2000);
return deferred.promise;
}
return {
getMessage : x
}
}])
.controller('HelloCtrl', ['$scope', 'MessageResolver', function($scope, MessageResolver)
{
$scope.messages = MessageResolver.getMessage();
}])
.config(['$routeProvider', function($routeProvider)
{
$routeProvider.when('/',
{
templateUrl: 'index2.html',
controller: "HelloCtrl",
resolve: ['MessageResolver']
});
}])
;
感谢您的帮助。
答案 0 :(得分:0)
来自文档:
factory - {string | function}:如果是string,则它是服务的别名。否则,如果是函数,则将其注入,并将返回值视为依赖项。
因此,您的service
必须返回要解决的承诺。试试这个:
var resolver = ['$q', '$timeout', function($q, $timeout)
{
var deferred = $q.defer();
$timeout(function()
{
deferred.resolve(['Hello', 'world!']);
}, 2000);
return deferred.promise;
}]
// ...
.config(['$routeProvider', function($routeProvider)
{
$routeProvider.when('/',
{
templateUrl: 'index2.html',
controller: "HelloCtrl",
resolve: { 'MessageResolver': resolver }
});
}])
如果您想将其用作服务:
angular.module('myModule', ['ngRoute'])
.factory('MessageResolver', ['$q', '$timeout', function($q, $timeout)
{
var deferred = $q.defer();
$timeout(function()
{
deferred.resolve(['Hello', 'world!']);
}, 2000);
return deferred.promise;
}])
.controller('HelloCtrl', ['$scope', 'MessageResolver', function($scope, MessageResolver)
{
MessageResolver.then(function(messages)
{
$scope.messages = messages;
})
}])
.config(['$routeProvider', function($routeProvider)
{
$routeProvider.when('/',
{
templateUrl: 'index2.html',
controller: "HelloCtrl",
resolve: { 'MessageResolver': 'MessageResolver' }
});
}])