Error and Mysql: [ngRepeat:dupes] Duplicates in a Repeater are

Asked

Viewed 615 times

0

I’m developing an example with IONIC but it’s giving the error:

ionic.bundle.js:19387 Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: usuario in usuarios, Duplicate key: string:c, Duplicate value: c
http://errors.angularjs.org/1.3.6/ngRepeat/dupes?p0=usuario%20in%20usuarios&p1=string%3Ac&p2=c
    at ionic.bundle.js:7888
    at ngRepeatAction (ionic.bundle.js:32262)
    at Object.$watchCollectionAction [as fn] (ionic.bundle.js:21887)
    at Scope.$digest (ionic.bundle.js:22020)
    at Scope.$apply (ionic.bundle.js:22282)
    at done (ionic.bundle.js:17439)
    at completeRequest (ionic.bundle.js:17629)
    at XMLHttpRequest.requestLoaded (ionic.bundle.js:17570)(anonymous function) @ ionic.bundle.js:19387(anonymous function) @ ionic.bundle.js:16350Scope.$digest @ ionic.bundle.js:22038Scope.$apply @ ionic.bundle.js:22282done @ ionic.bundle.js:17439completeRequest @ ionic.bundle.js:17629requestLoaded @ ionic.bundle.js:17570

I have already reviewed the code several times, I have tried to change in ng-repeat with other variables, but either the error disappears or it does not show the data. What can be?

My PHP:

    <?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: text/html; charset=utf-8");

$data = file_get_contents("php://input");
$objData = json_decode($data);

$dns = "mysql:host=mysql70.ramosdainformatica.com.br;dbname=ramosdainforma70";
$user = "usuario";
$pass = "senha";


$counter = $objData->counter;
$token = $objData->token;

try {   
    $con = new PDO($dns, $user, $pass);

    echo "Abriu con";

    if(!$con){
        echo "Não foi possivel conectar com Banco de Dados!";
    }
    if ($token === "1f3d2gs3f2fg3as2fdg3re2t1we46er45" && isset($token)) {  


        $query = $con->prepare('SELECT * FROM usuario_app ORDER BY nome LIMIT '.$counter.', 5');
        $query->execute();


        $out = "[";
        while($result = $query->fetch()){
            if ($out != "[") {
                $out .= ",";
            }
            $out .= '{"cod_user: "'.$result["cod_user"].'",';
            $out .= '"nome": "'.$result["nome"].'",';
            $out .= '"pais": "'.$result["pais"].'",';
            $out .= '"cep": "'.$result["cep"].'"';
            $out .= '"logradouro": "'.$result["logradouro"].'",';
            $out .= '"complemento": "'.$result["complemento"].'",';
            $out .= '"bairro": "'.$result["bairro"].'",';
            $out .= '"cidade": "'.$result["cidade"].'"';
            $out .= '"estado": "'.$result["estado"].'",';
            $out .= '"celular": "'.$result["celular"].'",';
            $out .= '"email": "'.$result["email"].'",';
            $out .= '"senha": "'.$result["senha"].'"';
            $out .= '"data_cadastro": "'.$result["data_cadastro"].'",';
            $out .= '"latitude": "'.$result["latitude"].'",';
            $out .= '"longitude": "'.$result["longitude"].'"}';            

        }
        $out .= "]";
        echo $out; 


    }
} catch (Exception $e) {
    echo "Erro: ". $e->getMessage();
};

My Controller:

    (function() {
    "use strict";

    angular.module("myApp").controller("initCtrl", function($scope, Data){
        $scope.home = "Usuários";
        $scope.perfil = "Perfil";

        $scope.usuarios = [];

        var getData = function(){
            var params = {
                counter:$scope.usuarios.length,
                token:"1f3d2gs3f2fg3as2fdg3re2t1we46er45",
            };

            Data.getData(params).success(function(data) {
                    $scope.usuarios = data;
            }).error(function(data) {
                console.log(data? data: "Não foi possível acessar ao banco de dados.");
            });


        };

        getData();



});
})();

My Service:

    (function(){
    "use strict";

    angular.module("myApp").value("Config", {

        getUrl: "http://www.ramosdainformatica.com.br/food/"
    });

    angular.module("myApp").service("Data", function($http, Config){
        //recuperação de dados
        this.getData = function(params){
            return $http({
                method: "POST",
                url: Config.getUrl + "apinhac.php",
                data: params,
                headers : {
                                'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
                            }
            });
        };


    });
})();

My HTML list:

<ion-view view-title="{{home}}">        

    <ion-content>
        <h1>{{home}}</h1>

        <ion-list ng-repeat="usuario in usuarios">

            <ion-item>
                <h1 class="assertive">{{usuario.nome}}</h1>
                <p>{{usuario.email}}</p>
            </ion-item>

        </ion-list>

    </ion-content>
    </ion-view>

I have already reviewed the code several times, I have tried to change in ng-repeat with other variables, but either the error disappears or it does not show the data. What can be?

  • Bro took a look at your code apparently it’s all right I also work with Ionic and Angular Js .... The suspicion here is that there must be some component missing in your application that relates to Angular or Ionic what I advise you is to use the INTEL XDK to work with Ionic there you do not need to install anything or download something else will make you much easier.

2 answers

1

It turns out that the property that the angular is using to be the key to its loop, is repeating at some point within its repetition. Try using another key, one you are sure is unique. For this use the expression "track by" in your ng-repeat.

Example:

<ion-list ng-repeat="usuario in usuarios track by usuario.email">
  • The error continues.

  • In your controler use console.log($Scope.usuarios), paste the result somewhere hiding the confidential data and post here please

  • @Ramos Check if you have any duplicate lines in your user array

  • Well, the log is accessing and reading the table, so I saw nothing duplicated: Opened with[{"cod_user: "1","name": "test user","parents": "Brasil","cep": "38300070""patiouro": "Rua Dezesseis, 1511","complement": ""","neighborhood": "Centro","city": "Ituiutaba""state": "MG","cellular": "3432610020","email": "[email protected]","password": "testeapp""data_cadastro":": ""}]

  • try using track by user.cod_user (note that user is not in plural)

  • Error continues: <ion-list ng-repeat="user in usuarios track by user.cod_user">

  • In fact, it worked now... but no longer access the database... rs.

  • Our haha that bizarre, is logging something on the console?

  • Console informs message I left: Unable to access database.

  • yntaxError: Unexpected number at Object.parse (Native) at fromJson (http://localhost:8100/Ionic/js/Ionic.bundle.js:8883:14) at defaultHttpResponseTransform (http://localhost:8100/Ionic/js/Ionic.bundle.js:16368:14) at http://localhost:8100/Ionic/js/Ionic.bundle.js:16445:12 at foreach (http://localhost:8100/Ionic/js/Ionic.bundle.js:8147:20) at transformData (http://localhost:8100/Ionic/js/Ionic.bundle.js:16444:3) at transformResponse (http://localhost:8100/Ionic/js/Ionic.bundleonic.js:17171:23) at processQueue

  • Xmlhttprequest cannot load http://www.ramosdainformatica.com.br/food/apinhac.php. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:8100' is therefore not allowed access.

  • Add this at the beginning of the file apinhac.php: header('Access-Control-Allow-Origin: *');

  • It’s already like that...

  • You are using jsonp?

Show 9 more comments

1

As stated in friend Ziron’s reply, you should make sure that the element used in the track by be unique, not repeated in another element. For example, a id obtained from the database.

For this we use the option track by to follow up the loop based on this index. BUT if you don’t own or don’t know if you have a unique value, or simply don’t want to use a track based on its properties, you can use the $index which is the position of the object within the array, that is, it will always be unique, because there is only a 1st element, a 2nd element, etc..

Use like this: ng-repeat="usuario in usuarios track by $index"

  • Hi Celsom, now the error is: Xmlhttprequest cannot load http://www.ramosdainformatica.com.br/food/apinhac.php. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:8100' is therefore not allowed access.

Browser other questions tagged

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