How to limit the amount of items listed using Ionic and JSON?

Asked

Viewed 338 times

0

I decided to popular my table with 55,000 items.

The result link is here:

http://vovocooks.com.br/admin/apis/api_listagem/lista_oferta_api.php?json=promocao&latitude=-18.9795075&longitude=-49.1&raio=30

Now my app can’t read everything. I need to limit reading. I’m not sure how to do it.

Follow my controller:

.controller("promocoesCtrl", function ($scope, $rootScope, $state, $ionicScrollDelegate, $http, $httpParamSerializer, $stateParams, $timeout, $ionicLoading, $ionicPopup, $ionicPopover, $ionicSlideBoxDelegate, $ionicHistory, ionicMaterialInk, ionicMaterialMotion, $ionicModal, sharedCartService, sharedFilterService, $ionicNavBarDelegate, $ionicPlatform, $cordovaKeyboard, $filter) {

    window.localStorage.removeItem("data_ofertass");

    $scope.raio = '30';

    $scope.sttButton = false;

    window.localStorage.getItem("endereco_temp");
    window.localStorage.getItem("endereco_atual");

    //put cart after menu
    var cart = sharedCartService.cart;

    var len = cart.length;


    console.log('quantidade de itens no carrinho' + len);

    $ionicModal.fromTemplateUrl('templates/filters/side-filter.html', {
        scope: $scope
    }).then(function (modal) {
        $scope.modal = modal;
    });


    $scope.endereco_atual = window.localStorage.getItem("endereco_atual");

    if (window.localStorage.getItem("user_des") === undefined) {
        console.log("Usuário logado, setar como logado");



    } else {

        console.log("Usuário deslogado, setar como deslogado");
        var setar = "user_des";
        window.localStorage.setItem("user_des", setar)
    };





    $scope.cadastra_oferta_cod_fornecedor = $stateParams.cadastra_oferta_cod_fornecedor;

    $scope.endereco_atual = window.localStorage.getItem("endereco_atual");


    // ORDENA POR...
    $scope.selectableNames = [

        {
            name: "por preço - do menor ao maior",
            role: "+cadastra_oferta_valor_com_desconto"
        },

        {
            name: "por preço - do maior ao menor",
            role: "-cadastra_oferta_valor_com_desconto"
        },
        {
            name: "valor do frete - menor ao maior",
            role: "fornecedor_configura_frete_custo_padrao"
        },
        {
            name: "desconto (%) - do maior ao menor",
            role: "-cadastra_oferta_desconto"
        },

        {
            name: "desconto (%) - do menor ao maior",
            role: "+cadastra_oferta_desconto"
        },


        {
            name: "avaliação - da maior a menor",
            role: "-media_avaliacao"
        },

        {
            name: "avaliação - da menor a maior",
            role: "+media_avaliacao"
        },
        {
            name: "ordem alfabética",
            role: "+cadastra_oferta_titulo_promocao"
        },
        {
            name: "tempo de entrega - do menor ao maior",
            role: "+fornecedor_configura_frete_prazo_entrega_min"
        },



//        {
//            name: "Por Menor valor de Frete",
//            role: "+fornecedor_configura_frete_custo_padrao"
//        },

    ];


    $scope.getOpt = function (option) {
        return option.name + ":" + option.role;
        console.log(option.role);
        window.localstorage.setItem("OrdenaPor", option.role);

        var op = window.localstorage.getItem("OrdenaPor");

        var option = parseFloat(Math.round(op * 100) / 100).toFixed(2);



    };
    // FIM DE ORDENA POR



    // PEGA OS ITENS SELECIONADOS NA MODAL E COLOCA NUM ARRAY
    $scope.checkItems = {};

    $scope.print = function () {
        console.log($scope.checkItems);

        //      window.localStorage.setItem("q", $scope.checkItems);

        //        $scope.q = window.localStorage.getItem("q");

        //        $scope.closeModal();
    }

    // APLICANDO FILTRO CATEGORIA
    //$scope.userCategoria = function (checkItems) {
    //    console.log("entra na chamada");

    //     $scope.modal.hide();


    //};

    $scope.save = function (checkItems) {
        console.log("Chamou o save");
        var array = [];
        for (i in $scope.checkItems) {
            console.log($scope.checkItems[i]);
            if ($scope.checkItems[i] == true) {
                array.push(i);

            }
        }
        console.log(array);

        window.localStorage.setItem("q", $scope.checkItems[i]);

        $scope.q = window.localStorage.getItem("q");

        $scope.modal.hide()
    };

    $scope.limpaFiltro = function () {

        var limpa = '';

        window.localStorage.setItem("q", limpa);

        $scope.q = window.localStorage.removeItem("q");

        $scope.doRefresh()

        $scope.modal.hide();

        //    $scope.doRefresh();

    };

    $scope.mudaraio = function (raio) {
        $scope.raio = raio;
        $scope.doRefresh();
        $scope.modal.hide()

    };



    $rootScope.page_id = "promocoes";


    $scope.getStars = function (avalia) {
        // Get the value
        var val = parseFloat(avalia);
        // Turn value into number/100
        var size = val / 5 * 100;
        return size + '%';
    }

    //            $scope.ratingsCallback = function (rating, index) {
    //                console.log('Selected rating is : ', rating, ' and the index is : ', index);
    //            };


    // DELICIA   
    $scope.ratingsObjectAvaliacao_Geral = {
        iconOn: 'ion-ios-star',
        iconOff: 'ion-ios-star-outline',
        iconOnColor: 'rgb(200, 200, 100)',
        iconOffColor: 'rgb(200, 100, 100)',
        rating: 0,
        minRating: 0,
        callback: function (rating) {
            $scope.ratingsCallbackAvaliacaoGera(rating);

        }
    };

    $scope.ratingsCallbackAvaliacaoGeral = function (rating) {
        $scope.avaliacao_geral_star = rating;
    };




    window.localStorage.getItem("endereco_temp");


    $scope.endereco_atual = window.localStorage.getItem("endereco_atual");


    $scope.scrollTop = function () {
        $ionicScrollDelegate.$getByHandle("top").scrollTop();
    };
    // open external browser 
    $scope.openURL = function ($url) {
        window.open($url, "_system", "location=yes");
    };
    // open AppBrowser
    $scope.openAppBrowser = function ($url) {
        window.open($url, "_blank", "closebuttoncaption=Done");
    };
    // open WebView
    $scope.openWebView = function ($url) {
        window.open($url, "_self");
    };

    $scope.lat_cliente = window.localStorage.getItem("latitude");

    $scope.long_cliente = window.localStorage.getItem("longitude");

    $scope.endereco_atual = window.localStorage.getItem("endereco_atual");

    $scope.numberOfItemsToDisplay = 20; // number of item to load each time

    // Set Motion
    $timeout(function () {
        ionicMaterialMotion.slideUp({
            selector: ".slide-up"
        });
    }, 300);


    var targetQuery = ""; //default param
    var raplaceWithQuery = "";
    // TODO: Dinamics Promoções


    targetQuery = "json=promocao"; //default param
    raplaceWithQuery = "json=promocao";


    var fetch_per_scroll = 1;
    // animation loading 
    $ionicLoading.show({
        template: '<div class="loader"><svg class="circular"><circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/></svg></div>'
    });


    $scope.noMoreItemsAvailable = false; //readmore status
    var lastPush = 0;
    var data_ofertass = [];

    $scope.endereco_atual = window.localStorage.getItem("endereco_atual");

    if (window.localStorage.getItem("data_ofertass") !== "undefined") {
        data_ofertass = JSON.parse(window.localStorage.getItem("data_ofertass"));
        if (data_ofertass !== null) {
            $scope.ofertass = [];
            for (lastPush = 0; lastPush < 10; lastPush++) {
                if (angular.isObject(data_ofertass[lastPush])) {
                    $scope.ofertass.push(data_ofertass[lastPush]);
                };
            }

            $timeout(function () {
                $ionicLoading.hide();
            }, 500);



        }
    }
    if (!angular.isObject(data_ofertass)) {
        $timeout(function () {
            // retry retrieving data
            $http.get("http://vovocooks.com.br/admin/apis/api_listagem/lista_oferta_api.php?json=promocao" + "&latitude=" + $scope.lat_cliente + "&longitude=" + $scope.long_cliente + "&raio=" + $scope.raio.replace(targetQuery, raplaceWithQuery)).then(function (response) {
                data_ofertass = response.data;
                if (typeof (Storage) != "undefined") {
                    try {                        
                        window.localStorage.setItem("data_ofertass", JSON.stringify(data_ofertass));
                        console.log("Sem resultado");
                    } catch (e) {
                        window.localStorage.clear();
                        window.localStorage.setItem("data_ofertass", JSON.stringify(data_ofertass));
                        $state.reload();
                        $scope.$state = $state;
                        console.log("Depois do catch");

                        window.localStorage.getItem("endereco_temp");
                        window.localStorage.getItem("endereco_atual");

                    }
                }

                if (window.localStorage.getItem("data_ofertass") === '[]') {

                    $ionicHistory.nextViewOptions({
                        disableBack: false,
                        historyRoot: true
                    });

                    $ionicHistory.clearCache();
                    $ionicHistory.clearHistory();


                    $state.go("nhaac.nachegamos");


                }


                $scope.ofertass = [];
                for (lastPush = 0; lastPush < 100; lastPush++) {
                    if (angular.isObject(data_ofertass[lastPush])) {
                        $scope.ofertass.push(data_ofertass[lastPush]);
                    };
                }
            }, function (response) {
                // error message
                var alertPopup = $ionicPopup.alert({
                    title: "error " + response.status,
                    template: response.statusText + "<br/>Problema: Conexão com sua Internet.",
                });
            }).finally(function () {
                console.log("finally....");
                $scope.$broadcast("scroll.rfreshComplete");
                // event done, hidden animaion loading


                $timeout(function () {
                    $ionicLoading.hide();
                }, 1000);
            });

        }, 1000);
    } else {
        console.log("Realmente vazio...");
    }



    $scope.doRefresh = function () {
        // retry retrieving data
        //  window.localStorage.clear();
        $http.get("http://vovocooks.com.br/admin/apis/api_listagem/lista_oferta_api.php?json=promocao" + "&latitude=" + $scope.lat_cliente + "&longitude=" + $scope.long_cliente + "&raio=" + $scope.raio.replace(targetQuery, raplaceWithQuery)).then(function (response) {
            data_ofertass = response.data;
            if (typeof (Storage) != "undefined") {
                try {
                    window.localStorage.setItem("data_ofertass", JSON.stringify(data_ofertass));
                    console.log("Sem resultado 2");
                } catch (e) {
                    window.localStorage.clear();
                    window.localStorage.setItem("data_ofertass", JSON.stringify(data_ofertass));
                    $state.reload();
                    $scope.$state = $state;

                    window.localStorage.getItem("endereco_temp");
                    window.localStorage.getItem("endereco_atual");


                }
            }

            if (response = "nao_nesta_regiao") {
                console.log("A resposta veio nao_nesta_regiao")
            }

            $scope.ofertass = [];
            for (lastPush = 0; lastPush < 100; lastPush++) {
                if (angular.isObject(data_ofertass[lastPush])) {
                    $scope.ofertass.push(data_ofertass[lastPush]);
                };
            }
        }, function (response) {
            // error message
            var alertPopup = $ionicPopup.alert({
                title: "error " + response.status,
                template: response.statusText + "<br/>Problema: Conexão com sua Internet.",
            });
        }).finally(function () {
            $scope.$broadcast("scroll.refreshComplete");
            // event done, hidden animation loading
            $timeout(function () {
                $ionicLoading.hide();
            }, 500);
        });



    };


    if (data_ofertass === null) {
        data_ofertass = [];
        console.log("se data_ofertass é vazio");

        window.localStorage.getItem("endereco_temp");
        window.localStorage.getItem("endereco_atual");
    };








    $scope.ordenarLista = function () {
        // Explicando: $filter('orderBy')( "lista a ser ordenada", "campos para ordenar");
        // Ex.: $filter('orderBy')( $scope.ofertas, ['nome', 'valor', '-idade']);

        $scope.ofertass = $filter('orderBy')($scope.ofertass, -cadastra_oferta_desconto); // Lista com a nova ordem
    };




    //Coloca produto em destaque
    $scope.addToStar = function (id, image, name, price, supply_id, deliver) {

        console.log(id);
        console.log(name);
        console.log(price);
        console.log(supply_id);




    };


    //add to cart function
    $scope.addToCart = function (id, image, name, price, supply_id, deliver, entrega) {
        // CHAMA CART.ADD DE SERVICES 
        window.localStorage.setItem("fonecedor_carrinho", supply_id);
        window.localStorage.setItem("tipos_pagamentos", tipopag);
        window.localStorage.setItem("frete", deliver);
        window.localStorage.setItem("faz_entrega", entrega);
        cart.add(id, image, name, price, 1, supply_id, deliver);
        $state.go("nhaac.carrinho");

    };

    // animation readmore
    var fetchItems = function () {
        console.log("fetch?");
        for (var z = 0; z < fetch_per_scroll; z++) {
            if (angular.isObject(data_ofertass[lastPush])) {
                $scope.ofertass.push(data_ofertass[lastPush]);
                lastPush++;
            } else {;
                $scope.noMoreItemsAvailable = true;
                console.log("else do fetch?");
            }
        }
        $scope.$broadcast("scroll.infiniteScrollComplete");
    };



    var tipo = '';

    // $scope.checarPermissoes();

    $scope.checarPermissoes = function (tipo) {
        var permitido;

        if (tipo === 'logado_usuario' && window.localStorage.getItem("user_log") === 'user_log') {
            permitido = true;
        } else {
            permitido = false;
        }

        return permitido;
    };




    // event readmore
    $scope.onInfinite = function () {
        $timeout(fetchItems, 500);
    };

    // create animation fade slide in right (ionic-material)
    $scope.fireEvent = function () {
        ionicMaterialMotion.fadeSlideInRight();
        ionicMaterialInk.displayEffect();
    };


    // INICIA FILTRO POR CATEGORIA    
    //    $ionicModal.fromTemplateUrl('/templates/filters/side-filter.html', {
    //        scope: $scope,
    //        animation: 'slide-in-up'
    //    }).then(function (modal) {
    //        $scope.modal = modal;
    //    });
    //    $scope.abreModal = function () {
    //        $scope.modal.show();
    //    };
    //    $scope.closeModal = function () {
    //        $scope.modal.hide();
    //    }

    $scope.scrollToTop = function () { //ng-click for back to top button
        $ionicScrollDelegate.scrollTop();
        $scope.sttButton = false;
    };

    $scope.getScrollPosition = function () {
        //monitor the scroll
        var moveData = $ionicScrollDelegate.getScrollPosition().top;
        // console.log(moveData);

        if (moveData > 150) {
            $scope.$apply(function () {
                $scope.sttButton = true;
            }); //apply
        } else {
            $scope.$apply(function () {
                $scope.sttButton = false;
            }); //apply
        }

    }; //getScrollPosition

    $scope.fechaTeclado = function () {
        $cordovaKeyboard.close()
    };


    $scope.mudar_localizacao = function () {
        window.localStorage.removeItem("latitude");
        window.localStorage.removeItem("longitude");
        window.localStorage.removeItem("fornecedor_carrinho");
        window.localStorage.removeItem("tipos_pagamentos");
        window.localStorage.removeItem("frete");
        window.localStorage.removeItem("total_pedido");
        window.localStorage.removeItem("array2");
        window.localStorage.removeItem("forma_pagamento_selecionada");
        window.localStorage.removeItem("outro_endereco_entrega");
        window.localStorage.removeItem("observacao");
        window.localStorage.removeItem("id_pedido");
        window.localStorage.removeItem("endereco_temp");
        window.localStorage.removeItem("entrega_bairro");
        window.localStorage.removeItem("entrega_cidade");
        window.localStorage.removeItem("entrega_endereco");
        window.localStorage.removeItem("entrega_estado");
        window.localStorage.removeItem("entrega_id_cliente");
        window.localStorage.removeItem("entrega_numero");
        window.localStorage.removeItem("entre_vai_pegar");
        window.localStorage.removeItem("frete");
        window.localStorage.removeItem("faz_entrega");
        window.localStorage.removeItem("fonecedor_carrinho");
        window.localStorage.removeItem("data_ofertass");
        window.localStorage.removeItem("troco");
        window.localStorage.removeItem("data_restaurantess");
        window.localStorage.removeItem("Agrupar");

        window.localStorage.removeItem("valor_troco_tela_troco");
        window.localStorage.removeItem("pedido_selecionado");
        window.localStorage.removeItem("p_observacoes");

        window.localStorage.removeItem("mesmo_end");
        window.localStorage.removeItem("cod_vovo_pedido");
        window.localStorage.removeItem("status_pedido");
        window.localStorage.removeItem("endereco_atual");
        window.localStorage.removeItem("endereco_gps");

        $state.go("nhaac.localiza", {}, {
            reload: true
        });


    };







    // animation ink (ionic-material)
    ionicMaterialInk.displayEffect();
    $scope.rating = {};
    $scope.rating.max = 5;



})

And my View:

<ion-view view-title="vovócooks" hide-back-button="false" show-side-menu="true" id="page-promocoes" class="has-header page-promocoes">



    <!-- BOTÃO CARRINHO DE COMPRAS -->
    <ion-nav-buttons side="right" class="has-header">
        <a href="#/nhaac/carrinho" class="button button-clear button-icon icon ion-ios-cart"> {{itens_no_carrinho}} </a>



        <!--     <button class="button button-clear button-icon ion-android-funnel" ng-model="q" ng-click="modal.show()"></button>  -->



    </ion-nav-buttons>


    <center>
        <form ng-submit="fechaTeclado()">
            <div class="bar bar-subheader bar-light">
                <label class="item item-input item-floating-label">
                    <i class="icon ion-search placeholder-icon"></i>
                    <input type="text" size="100" ng-model="q" placeholder="Procurar" type="submit" ng-submit="fechaTeclado()" ng-click="fechaTeclado()" />
                    <input type="submit" id="submit" value="OK" ng-click="fechaTeclado()" />

                </label>
            </div>
        </form>
    </center>





    <div class="tabs-striped tabs-top tabs-background-assertive tabs-color-light">
        <div class="tabs" style="height:70px;">
            <a class="tab-item active" href="#/nhaac/promocoes">
                <i class="icon ion-home"></i> DELÍCIAS CASEIRAS
            </a>
            <a class="tab-item" href="#/nhaac/restaurantes">
                <i class="icon ion-star"></i> VOVÓS ONLINE
            </a>
        </div>
    </div>



    <div class="tabs-striped tabs-color-assertive">
        <div class="tabs">
            <a class="tab-item active" ng-click="doRefresh()">
                <i class="icon ion-refresh"></i> Atualizar
            </a>

            <a ng-show="checarPermissoes('logado_usuario')" class="tab-item active" href="#/nhaac/perfil">
                <i class="icon ion-person"></i> Meu Perfil
            </a>
        </div>
    </div>



    <ion-content delegate-handle="top" lazy-scroll>

        <ion-refresher pulling-text="Puxe para atualizar..." on-refresh="doRefresh()"></ion-refresher>


        <div class="list animate-fade-slide-in-right">

            <div class="spacer" style="width: 300px; height: 65px;"></div>



            <div class="card">
                <div class="item" style="white-space:normal;font-size:12px">
                    <center>
                        <b>Localização Aproximada: </b> {{endereco_atual}} {{endereco_gps}}
                    </center>
                </div>

                <center>
                    <button class="button button-full button-assertive" style="font-size:12px" ng-click="mudar_localizacao()">
                        Mudar Localização
                    </button>
                </center>
            </div>

            <div class="button-bar">


            </div>



            <div class="card" ng-repeat="item in ofertass | filter:q | orderBy:someModel | unique: 'cadastra_oferta_cod_oferta' | limitTo:numberOfItemsToDisplay" ng-init="$last ? fireEvent() : null" href="#/nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}">


                <div class="item item-thumbnail-top item-text-wrap">
                    <img class="imagemCapa" image-lazy-loader="lines" ng-src="{{item.cadastra_oferta_foto}}" />
                    <div class="promocao"><b>{{item.cadastra_oferta_desconto}}% Off</b></div>
                    <div class="desconto"><b>{{item.cadastra_oferta_valor_com_desconto | currency}}</b></div>

                    <div class="item">
                        <center>
                            <h2 style="white-space:normal; color:#D95B43;"><b>{{item.cadastra_oferta_titulo_promocao}}</b></h2>
                        </center>
                    </div>

                    <div class="spacer" style="width: 300px; height: 8px;"></div>

                    <h3><b>Vovó Cozinheira: </b>{{item.fornecedores_fantasia}}</h3>



                    <h3 ng-hide="{{item.media_avaliacao === null}}" style="color:#D95B43;">Avaliação: <span class="stars alignright"> 
                       <span ng-style="{ 'width': getStars(item.media_avaliacao) }"></span> </span></h3>


                    <div class="spacer" style="width: 300px; height: 8px;"></div>

                    <div class="item">
                        <h3>Categoria: {{item.categoria_comida_nome}}</h3>

                        <h3><small><b>Descrição: </b>{{item.cadastra_oferta_descricao}}</small></h3>

                        <h3>
                                Preço Normal: <s style="color:red;"><small class="preco"> {{item.cadastra_oferta_valor_sem_desconto | currency}}</small></s><br> Preço Promocional: <small class="preco"> {{item.cadastra_oferta_valor_com_desconto | currency}} </small><br> Preço do Frete: <small class="preco"> {{item.fornecedor_configura_frete_custo_padrao | currency}} </small><br>
                                <b style="color:#D95B43;">Estoque disponível: </b><small class="preco"> {{item.cadastra_oferta_qtd_estoque}} </small>

                            </h3>


                    </div>
                </div>



                <a class="item button button-clear button-assertive ink" href="#nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}"><b>MAIS INFORMAÇÕES</b></a>
            </div>
        </div>



        <ion-list class="list">
            <ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="onInfinite()" distance="5px" ng-if="hasMoreData"></ion-infinite-scroll>
        </ion-list>



        <ion-list class="list">
            <div class="item" ng-if="results.length == 0">
                <p>Nenhum resultado encontrado...</p>
            </div>
        </ion-list>


    </ion-content>

    <div class="float-button" ng-click="scrollToTop()">
        <span class="height-fix">
            <a class="content">
              <i class="ion-jet"> </i>
            </a>
        </span>
    </div>

    <div class="pcss3rm pcss3rm-pos-bl pcss3rm-effect-fade">
        <input type="checkbox">
        <a href="#" class="color-red hcolor-red">
            <i class="color-white hcolor-white ion-funnel"></i>
        </a>
        <ul>

            <li> <a class="color-green hcolor-white" modal-select="" ng-model="someModel" options="selectableNames" option-property="role" modal-title="Ordenar por..." header-footer-class="bar-assertive"><i class="color-white hcolor-white ion-shuffle"></i>
                    <div class="option">                       
                        <h2>{{option.name}}</h2>
        </div>
        </a>
            </li>

            <li>
                <a class="color-yellow hcolor-white" ng-model="q" ng-click="modal.show()"><i class="color-white hcolor-white ion-android-funnel"></i></a>


            </li>



        </ul>
    </div>



    <!-- ./content -->
</ion-view>

How can I read this JSON and go listing from 10 to 10, as the user scrolls the page?

  • 1

    You can pass as parameter the limit for your server and limit it in the source. Even if you didn’t crash your app, internet consumption can make the user stop using your app.

  • 1

    As @Robertofagundes said, one option is to paginate the data on the server side, If your app needs to download all the information at once (like allowing offline queries for example) you can use a database on the app side to make the filtered queries, one that I think may be useful is the PouchDB, most there are many other DB to the client side

  • I’ll test these tips...

  • Solved. Thank you guys.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.