栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Angular $ http vs服务vs ngResource

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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注入到控制器定义的顶部。

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团队关于“最佳做法”的精彩视频,我仍在重新观看,并逐渐吸收。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380865.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号