大佬教程收集整理的这篇文章主要介绍了Angular $ http vs服务vs ngResource,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
决定将其表达为答案,因为在评论中我们基本上得出了您想知道的内容:
使用$ http或$ resource仍然可以缓存结果,您指出了在问题中真正使用一个结果的原因。如果您具有RESTful接口,那么使用$ resource会更好,因为最终您将编写更少的RESTful接口通用的样板代码,如果您不使用RESTful服务,则$ http更有意义。您可以使用以下两种方法之一来缓存数据:http://www.pseudobry.com/power-up-http-with- caching/
我认为将$ http或$ resource请求放入服务通常效果更好,因为您希望从多个位置访问数据,并且该服务充当一个单例对象。因此,基本上,您可以在此处处理任何类型的缓存,并且控制器都可以仅监视适当的服务来更新自己的数据。我发现控制器中的$ watch组合用于获取服务上的数据,并从服务的方法中返回承诺,这使我在如何更新控制器中的内容方面具有最大的灵活性。
我将这样的东西放入控制器中,并将exampleservice注入到控制器定义的顶部。
@H_262_10@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团队关于“最佳做法”的精彩视频,我仍在重新观看,并逐渐吸收。
以上是大佬教程为你收集整理的Angular $ http vs服务vs ngResource全部内容,希望文章能够帮你解决Angular $ http vs服务vs ngResource所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。