Javascript 如何在AngularJS中获得服务方法的结果?
我有以下代码:Javascript 如何在AngularJS中获得服务方法的结果?,javascript,angularjs,angularjs-service,Javascript,Angularjs,Angularjs Service,我有以下代码: PostApp.factory('loadPage', function ($http) { return { loadOtherPage: function (page, status, permition, order, cultureId) { $http({ url: '/Administrator/Post/PagedIndex', method: "POST", data:
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;
});
}
};
}))
))
但不要将中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;
});
};
非常好。但我在服务中的loadOtherPage函数中返回数据:$http({url:'/Administrator/Post/PagedIndex',方法:“Post”,数据:{…});tanks.
.success(函数(数据){return data;})
在请求成功时只注册一个额外的回调<代码>返回数据不是loadOtherPage
的return
语句。这是您要赋予success()
的匿名函数的return
语句。函数式语言是个婊子,我知道…:P
$scope.loaddata = function () {
var loadPagePromise = loadPage.loadOtherPage( ... );
loadPagePromise.success(function(data) {
$scope.ListOfItems = data;
});
};