2013-11-15 43 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

我會編輯我的答案清晰 –

相關問題