我想了解使用简单的 $http
请求到服务器和/或将该请求包装在服务中与使用 ngResource 对象相比的优点和缺点(除了关于RESTful 资源)。
根据我的理解,$http
请求是低级别的,但非常灵活且可配置,而在处理 RESTful API 时,ngResource 对象使通信非常简单。
我想我要询问的是一个非常简单的场景,比如从服务器检索数据(比如对象数组的 GET 请求),简单地使用 $http
是否更有效请求而不是将其包装在服务中(应该总是这样吗?)或使用 ngResource 对象?
如果有任何想法,我们将不胜感激。例如,$http
响应可以被缓存,但是 ngResource 可以吗?
最佳答案
决定将其表述为答案,因为在评论中我们基本上已经解决了您想知道的内容:
使用 $http 或 $resource 仍然可以缓存结果,您在问题中确实指出了使用其中之一而不是另一个的原因。如果您有 RESTful 接口(interface),那么使用 $resource 会更好,因为您最终将编写更少的 RESTful 接口(interface)常见的样板代码,如果您不使用 RESTful 服务,那么 $http 更有意义。您可以通过任何一种方式缓存数据http://www.pseudobry.com/power-up-http-with-caching/
我认为将 $http 或 $resource 请求放入服务中通常会效果更好,因为您希望能够从多个位置访问数据并且该服务充当单例。因此,基本上您可以处理您想要执行的任何类型的缓存,并且 Controller 都可以只监视适当的服务来更新自己的数据。我发现 Controller 中的 $watch 组合用于获取服务数据并从服务方法返回 promise ,这为我在更新 Controller 中的内容方面提供了最大的灵 active 。
我会将类似的内容放入 Controller 中,并在 Controller 定义的顶部注入(inject) exampleService。
angular.module("exampleApp", []).service('exampleService', ["$http", "$q" ,function ($http, $q) {
var service = {
returnedData: [],
dataLoaded:{},
getData = function(forceRefresh)
{
var deferred = $q.defer();
if(!service.dataLoaded.genericData || forceRefresh)
{
$http.get("php/getSomeData.php").success(function(data){
//service.returnedData = data;
//As Mark mentions in the comments below the line above could be replaced by
angular.copy(data, service.returnedData);
//if the intention of the watch is just to update the data
//in which case the watch is unnecessary and data can
//be passed directly from the service to the controller
service.dataLoaded.genericData = true;
deferred.resolve(service.returnedData);
});
}
else
{
deferred.resolve(service.returnedData);
}
return deferred.promise;
},
addSomeData:function(someDataToAdd)
{
$http.post("php/addSomeData.php", someDataToAdd).success(function(data){
service.getData(true);
});
}
};
service.getData();
return service;
}]).controller("ExampleCtrl", ["$scope", "exampleService", function($scope, exampleService){
//$scope.$watch(function() {return exampleService.returnedData}, function(returnedData){
// $scope.myModel.someData = returnedData;
//});
//if not using angular.copy() in service just use watch above
$scope.myModel.someData = exampleService.returnedData;
}]);
这里还有一段来自 Angular 团队关于最佳实践的精彩视频,我仍在重新观看并慢慢吸收该视频。
http://www.youtube.com/watch?v=ZhfUv0spHCY
特别是在服务与 Controller 方面: http://www.youtube.com/watch?v=ZhfUv0spHCY&t=26m41s
关于AngularJS $http vs 服务 vs ngResource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17667455/