Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

angularjs - Angular $http vs service vs ngResource

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 object (other than the obvious regarding a RESTful resource).

From my understanding the $http requests are low level but very flexible and configurable whereas when dealing with a RESTful API the ngResource objects make communication very simple.

I guess what I am enquiring about is given a very simple scenario, say retrieval of data from a server (GET request of array of objects say) is it more efficient to simply use a $http request as opposed to either wrapping it in a service (should this always be the case?) or using an ngResource object?

Any thoughts here would be appreciated. For example, a $http response can be cached, can an ngResource? Thanks.

question from:https://stackoverflow.com/questions/17667455/angular-http-vs-service-vs-ngresource

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...