小编典典

Angular $ http vs服务vs ngResource

angularjs

我想了解使用简单的$
http请求到服务器和/或将该请求包装在服务中与使用ngResource对象(相对于RESTful资源而言不是显而易见的)相比的优缺点。

据我了解,$ http请求是低级别的,但非常灵活且可配置,而当处理RESTful API时,ngResource对象使通信非常简单。

我想我要问的是一个非常简单的情况,比如说从服务器中检索数据(对象数组的GET请求)相对于将其包装在服务中,仅使用$ http请求会更有效。
(应该总是这样吗?)还是使用ngResource对象?

这里的任何想法将不胜感激。例如,可以缓存$ http响应,可以使用ngResource吗?谢谢。


阅读 206

收藏
2020-07-04

共1个答案

小编典典

决定将其表达为答案,因为在评论中我们基本上得出了您想知道的内容:

使用$ http或$ resource仍然可以缓存结果,您指出了在问题中真正使用一个结果的原因。如果您具有RESTful接口,那么使用$
resource会更好,因为最终您将编写更少的RESTful接口通用的样板代码,如果您不使用RESTful服务,则$
http更有意义。您可以使用以下两种方法之一来缓存数据:http://www.pseudobry.com/power-up-http-with-
caching/

我认为将$ http或$
resource请求放入服务通常效果更好,因为您希望从多个位置访问数据,并且该服务充当一个单例对象。因此,基本上,您可以在此处处理任何类型的缓存,并且控制器都可以仅监视适当的服务来更新自己的数据。我发现控制器中的$
watch组合用于获取服务上的数据,并从服务的方法中返回承诺,这使我在如何更新控制器中的内容方面具有最大的灵活性。

我将这样的东西放入控制器中,并将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团队关于“最佳做法”的精彩视频,我仍在重新观看,并逐渐吸收。

2020-07-04