Angular $http vs service vs ngResource

后端 未结 2 1315
眼角桃花
眼角桃花 2020-11-29 18:16

I would like to understand the advantages / disadvantages over using a simple $http request to a server and/or wrapping that request in a service versus using a ngResource o

相关标签:
2条回答
  • 2020-11-29 19:01

    Decided I'll formulate this into an answer since in the comments we worked out basically what you wanted to know:

    Using $http or $resource the results can still be cached, you pointed out the reasons to use one over the other really in your question. If you have a RESTful interface then using $resource is better since you'll end up writing less boiler-plate code that is common to a RESTful interface, if you're not using a RESTful service then $http makes more sense. You can cache data either way http://www.pseudobry.com/power-up-http-with-caching/

    I think putting $http or $resource requests into a service just generally works out better because you want to have access to the data from multiple locations and the service acts as a singleton. So, basically you can handle any kind of caching you want to do there and controllers can all just watch the appropriate services to update their own data. I've found that a combo of $watch in the controllers for data on the service and returning the promises from my service's methods gives me the most flexibility with how to update things in the controller.

    I'd put something like this in my controller having the exampleService injected at the top of the controller definition.

    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;
    }]);
    

    Also here's a nice video from the Angular team on Best Practices that I'm still re-watching and slowly absorbing over time.

    http://www.youtube.com/watch?v=ZhfUv0spHCY

    Specifically on services vs controllers: http://www.youtube.com/watch?v=ZhfUv0spHCY&t=26m41s

    0 讨论(0)
  • 2020-11-29 19:08

    There is one far more meaningful difference than whether they can be cached or not.

    Using a resource will remove the need to set up $watches on the service or the returned data. You will not have to work with promises at all either. Essentially, it eliminates the need to do any of what shaunhusain is doing above in his example.

    A call to a resource method returns an empty instance of the structure associated with that resource, and you can and should bind to it directly. This same instance will fill with data at some later time. Since you have bound to the instance, when it fills in, your display will update automatically.

    Resources can also provide an encapsulated means of transforming requests and responses of the services it provides, making it all invisible to the client of the resource.

    Resources are like services on steroids.

    0 讨论(0)
提交回复
热议问题