2013-11-15 41 views
0

我有这样的代码:如何在angular js中获取服务方法的结果?

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 varible。 响应是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是空的?

回答

1

(编辑:额外的清晰度添加变量)

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; 
    }); 
}; 
+0

很坦克。 但我loadOtherPage功能的服务回报数据: $ HTTP(网址:{url: '/管理/后/ PagedIndex', 方法: “POST”, 数据:{...}} )成功(功能(data){ return data; }); 坦克。 –

+0

'.success(函数(数据){返回数据;})'只需在请求成功时注册一个额外的回调函数。 'return data;'不是'loadOtherPage'的'return'语句。这是你在“success()”中给出的匿名函数的'return'声明。功能语言是一个婊子,我知道...:P –

+0

我会编辑我的答案清晰 –

相关问题