加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS 1.2在服务中存储数据数组

发布时间:2020-12-17 07:07:54 所属栏目:安全 来源:网络整理
导读:我有一个问题,寻求建议,如何将存储在服务数组中的数据提供给控制器,因为在1.2中删除了解包承诺. 例: 路线1包含项目列表 Route 2包含一个表单以添加新项目 一旦项目从路线牵引中保存,用户将被重定向回路线1. 当路由1初始加载时,服务将向服务器请求项目,将项
我有一个问题,寻求建议,如何将存储在服务数组中的数据提供给控制器,因为在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
        });  
    };
});

解决方法

您可以让服务返回自己的承诺,可以使用缓存值或$http承诺的结果来解决.我没有对此进行过全面测试,但它可能看起来像这样:

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数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读