3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
編輯:這個(gè)答案主要集中在版本1.0.X. 為了防止混淆,它將被更改以反映截至2013-12-05的所有當(dāng)前Angular版本的最佳答案。
我們的想法是創(chuàng)建一個(gè)服務(wù),該服務(wù)返回對(duì)返回?cái)?shù)據(jù)的承諾,然后在您的控制器中調(diào)用它并處理那里的承諾以填充您的$ scope屬性。
服務(wù)
module.factory('myService', function($http) {
return {
getFoos: function() {
//return the promise directly.
return $http.get('/foos')
.then(function(result) {
//resolve the promise as the data
return result.data;
});
}
}
});
控制者:
處理promise的then()方法并從中獲取數(shù)據(jù)。設(shè)置$ scope屬性,并執(zhí)行您可能需要執(zhí)行的任何操作。
module.controller('MyCtrl', function($scope, myService) {
myService.getFoos().then(function(foos) {
$scope.foos = foos;
});
});
In-View Promise Resolution(僅限1.0.X):
在Angular 1.0.X中,這里的原始答案的目標(biāo),承諾將得到View的特殊處理。當(dāng)他們解決時(shí),他們的解析值將綁定到視圖。這已在1.2.X中棄用
module.controller('MyCtrl', function($scope, myService) {
// now you can just call it and stick it in a $scope property.
// it will update the view when it resolves.
$scope.foos = myService.getFoos();
});

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
最佳做法是將$http呼叫抽象為向服務(wù)器提供數(shù)據(jù)的“服務(wù)”:
module.factory('WidgetData', function($http){
return {
get : function(params){
return $http.get('url/to/widget/data', {
params : params
});
}
}
});
module.controller('WidgetController', function(WidgetData){
WidgetData.get({
id : '0'
}).then(function(response){
//Do what you will with the data.
})
});
$http像這樣抽象調(diào)用將允許您跨多個(gè)控制器重用此代碼。當(dāng)與此數(shù)據(jù)交互的代碼變得更加復(fù)雜時(shí),這可能是必要的,您可能希望在控制器中使用數(shù)據(jù)之前處理數(shù)據(jù),并緩存該進(jìn)程的結(jié)果,這樣您就不必花時(shí)間重新處理它。
您應(yīng)該將“服務(wù)”視為應(yīng)用程序可以使用的數(shù)據(jù)的表示(或模型)。

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
接受的答案是給我$http is not defined錯(cuò)誤所以我必須這樣做:
var policyService = angular.module("PolicyService", []);
policyService.service('PolicyService', ['$http', function ($http) {
return {
foo: "bar",
bar: function (params) {
return $http.get('../Home/Policy_Read', {
params: params
});
}
};
}]);
這條線的主要區(qū)別是:
policyService.service('PolicyService', ['$http', function ($http) {
- 3 回答
- 0 關(guān)注
- 533 瀏覽
添加回答
舉報(bào)