如何在Angular JS中获取服务方法的结果?
-
20-12-2019 - |
题
我有这个代码:
PostApp.factory('loadPage', function ($http) {
return {
loadOtherPage: function (page, status, permition, order, cultureId) {
$http({
url: '/Administrator/Post/PagedIndex',
method: "POST",
data: { page: page, status: status, permition: permition, order: order, cultureId: cultureId }
}).success(function(data) {
return data;
});
}
};
});
PostApp.controller('PostController',
function ($scope, $http, loadPage) {
$scope.status = 'Published';
$scope.permition = 'Global';
$scope.order = 'Asscending';
$scope.cultureId = 1;
$scope.ListOfItems = [];
$scope.start = 2;
$scope.skip = 10;
$scope.loaddata = function () {
$scope.ListOfItems = loadPage.loadOtherPage($scope.start, $scope.status, $scope.permition, $scope.order, $scope.cultureId);
};
}
);
但不要将 loadPage.loadOtherPage 服务的响应设置为 $scope.ListOfItems 变量。浏览器控制台中的响应为 json:
[{"PId":15,"Id":15,"Status":"انتشار","Permition":"سراسری","PublishedDateEn":"08/19/2013","Title":"xxxxxxxxxxxx","CultureId":1,"Username":"naser","CommentCount":0},{"PId":16,"Id":16,"Status":"انتشار","Permition":"سراسری","PublishedDateEn":"08/19/2013","Title":"yyyyyyyyyyyyyyyyyy","CultureId":1,"Username":"naser","CommentCount":0},{"PId":17,"Id":17,"Status":"انتشار","Permition":"سراسری","PublishedDateEn":"08/21/2013","Title":"zzzzzzzzzzzzzzzz","CultureId":1,"Username":"naser","CommentCount":0}]
最终 $scope.ListOfItems 为空?
解决方案
(编辑:添加变量以更加清晰)
这 loadOtherPage
函数不返回任何内容,这就是为什么 $scope.ListOfItems
是空的。正确的方法是这样的:
loadOtherPage: function (page, status, permition, order, cultureId) {
var httpPromise = $http({
url: '/Administrator/Post/PagedIndex',
method: "POST",
data: { ... }
});
return httpPromise;
}
你基本上回报了这样的承诺 $http
返回,返回给调用者。你的控制器应该变成:
$scope.loaddata = function () {
var loadPagePromise = loadPage.loadOtherPage( ... );
loadPagePromise.success(function(data) {
$scope.ListOfItems = data;
});
};
不隶属于 StackOverflow