微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个问题,寻求建议,如何将存储在服务数组中的数据提供给控制器,因为在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数组.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐