大佬教程收集整理的这篇文章主要介绍了AngularJS 1.2在服务中存储数据数组,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
>路线1包含项目列表
> Route 2包含一个表单以添加新项目
>一旦项目从路线牵引中保存,用户将被重定向回路线1.
当路由1初始加载时,服务将向服务器请求项目,将项目存储在服务中的数组中,因此在此之后路由1的每个请求将返回一个数组.保存项目时,该项目被推送到服务中的数组.
如果我在初始加载时等待路由器1的控制器中的承诺,没有问题,因为响应被发回,但是之后路由一个的每个请求都会返回错误,因为我返回了一个数组.
关于如何在1.2中完成这样的事情的任何想法?
app.factory('Items',function($http) { var items = []; return { list: function() { if (items.length == 0) { // items array is empty so populate it and return list from server to controller return $http.get('/?items').then(function(responsE) { items = response.data.items; return response.data.items; }); } return items; // items exist already so just return the array },save: function(item) { return $http.post('/',{item:item}).then(function(responsE) { items.push(item); return response; }); } } }); app.controller('RouteOne',function($scope,Items) { Items.list().then(function(responsE) { $scope.items = response; }); /* used to be this before unwrapped promises were removed $scope.items = Items.list(); */ }); app.controller('RouteTwo',Items) { $scope.new_item = {}; $scope.addItem = function() { Items.save($scope.new_item).then(function(responsE) { $LOCATIOn.path('/'); // BACk to route one }); }; });
app.factory('Items',function($q,$http) { var items = []; return { list: function() { var deferred = $q.defer(); if (items.length == 0) { // items array is empty so populate it and return list from server to controller $http.get('/?items').then(function(responsE) { items = response.data.items; deferred.resolve(response.data.items); }); } else { deferred.resolve(items); // items exist already so just return the array } return deferred.promise; },Items) { Items.list().then(function(responsE) { $scope.items = response; }); });
此外,根据您的特定用例,您可以将延迟移动到服务级别而不是功能级别,因为您只需要调用一次,但我编写它的方式更灵活,以防您想要清除items数组.
以上是大佬教程为你收集整理的AngularJS 1.2在服务中存储数据数组全部内容,希望文章能够帮你解决AngularJS 1.2在服务中存储数据数组所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。