我正在读这篇文章:http://eviltrout.com/2013/06/15/ember-vs-angular.html
上面写着,
由于它缺乏约定,我想知道有多少Angular项目依赖于糟糕的做法,例如直接在控制器中调用AJAX?由于依赖注入,开发人员是否将路由器参数注入到指令中?新手AngularJS开发人员是否会以一种经验丰富的AngularJS开发人员认为惯用的方式来组织代码?
我实际上是从我的Angular.js控制器发出$http
调用。为什么这是一种糟糕的做法?那么,进行$http
调用的最佳实践是什么?为什么?
发布于 2013-07-15 12:28:58
EDIT:这个答案主要集中在1.0.X版本上。为了防止混淆,它被修改为反映目前所有当前版本的最佳答案,2013-12-05。
其思想是创建一个服务,将promise返回给返回的数据,然后在控制器中调用该服务,并在那里处理promise以填充$scope属性。
服务
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()
方法并从中获取数据。设置$scope属性,并执行您可能需要执行的任何其他操作。
module.controller('MyCtrl', function($scope, myService) {
myService.getFoos().then(function(foos) {
$scope.foos = foos;
});
});
视图内Promise Resolution (仅限1.0.X):
在Angular 1.0.X中,这里原始答案的目标,promises将得到视图的特殊对待。当它们解析时,它们的解析值将绑定到视图。在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();
});
发布于 2013-07-15 11:37:20
最佳实践是将$http
调用抽象为一个向控制器提供数据的“服务”:
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
调用将允许您跨多个控制器重用此代码。当与此数据交互的代码变得更加复杂时,这就变得很有必要,也许您希望在将数据用于控制器之前对其进行处理,并缓存该处理的结果,这样您就不必花费时间重新处理它。
您应该将“服务”视为您的应用程序可以使用的数据的表示(或模型)。
发布于 2014-08-21 03:16:29
被接受的答案是给我$http is not defined
错误,所以我必须这样做:
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
});
}
};
}]);
主要区别在于这一行:
policyService.service('PolicyService', ['$http', function ($http) {
https://stackoverflow.com/questions/17646034
复制相似问题