Problems with Promises from Angularjs

Asked

Viewed 171 times

1

I have the following function in Angularjs:

$scope.adicionarContato = function(contato) {
    contato.data = new Date();
    $http.post("http://localhost:3412/contatos", 
               contato).then(function successCallback(response) {
         delete $scope.contato;
         $scope.controlForm.$setPristine();
    }); 
};

I also have a form where it is possible to fill and add data through the JS angle:

<form name="controlForm">
    <input class="form-control" type="text" ng-model="contato.nome" name="nome" placeholder="Nome" ng-required="true" ng-minlength="10" />
    <input class="form-control" type="text" ng-model="contato.telefone" name="telefone" placeholder="Telefone" ng-required="true" ng-pattern="/^\d{4,5}-\d{4}$/" />
    <select class="form-control" ng-model="contato.operadora" ng-options="operadora.nome + ' ( ' + (operadora.preco | currency) + ' ) ' for operadora in operadoras | orderBy:'nome'">
        <option value="">Selecione uma Operadora</option>
    </select>
</form>

The method call is made by the button below:

<button class="btn btn-primary btn-block" ng-click="adicionarContato(contato)" ng-disabled="controlForm.$invalid">      Adicionar Contato
</button>

<button class="btn btn-danger btn-block" ng-click="apagarContatos(contatos)" ng-if="isContatoSelecionado(contatos)">Apagar Contato</button>

When I try to add a new contact by sending the data to the URL specified in the post method, the value passed, which refers to the content of the "contact" variable, is null. I checked that the webservice that is in the URL "http://localhost:3412/contacts" loads normally, but data is not transferred.

I tried to send this way too

$scope.adicionarContato = function(contato) {
    contato.data = new Date();
    $http.post("http://localhost:3412/contatos", contato1).then(function(response) {
        delete $scope.contato;
        $scope.controlForm.$setPristine();
    }); 
};

without the successCallback method, but continues as null.

Follow the controller:

angular.module("ListaTelefonica").controller("ListaTelefonicaCtrl", function ($scope, $http) {
    $scope.app = "Lista Telefonica";

    var carregarContatos = function() {
         $http.get('http://localhost:3412/contatos').then(function (response) {
              $scope.contatos = response.data;
        }).catch(function(response, status){
              $scope.message = "Erro: " + response.data;
        }); 
    }

    var carregarOperadoras = function() {
        $http.get('http://localhost:3412/operadoras').then(function (response) {
            $scope.operadoras = response.data;
        }); 
    }

    $scope.adicionarContato = function(contato) {
        contato.data = new Date();
        var config = {
              headers : {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
              }
        }
        $http.post("https://requestb.in/ped43xpe", contato, config).then(function successCallback(response) {
            console.log(contato);
            delete $scope.contato;
            $scope.controlForm.$setPristine();
        }); 
    };

    $scope.apagarContatos = function(contatos) {
        $scope.contatos = contatos.filter(function(contato) {
            if(!contato.selecionado) return contato;
        });
    };

    $scope.isContatoSelecionado = function (contatos) {
        return contatos.some(function (contato) {
            return contato.selecionado;
        });
    }

    $scope.ordernarPor = function (campo) {
        $scope.criterioDeOrdenacao = campo;
        $scope.direcaoDaOrdenacao = !$scope.direcaoDaOrdenacao;
    }

    carregarContatos();
    carregarOperadoras();
});

On the console, this message appears:

TypeError: Cannot read property 'some' of undefined
at b.$scope.isContatoSelecionado (index_diretivas.html:78)
at fn (eval at compile (angular.js:15584), <anonymous>:4:259)
at m.$digest (angular.js:18276)
at m.$apply (angular.js:18553)
at angular.js:1942
at Object.invoke (angular.js:5079)
at c (angular.js:1940)
at Wc (angular.js:1960)
at we (angular.js:1845)
at angular.js:34115

Can you explain what’s happening?

Update

Follow the controller:

    angular.module("ListaTelefonica").controller("ListaTelefonicaCtrl", function ($scope, $http) {
        $scope.app = "Lista Telefonica";
        // $scope.contatos = [];
        // $scope.operadoras = [];

        var carregarContatos = function() {
             $http.get('http://localhost:3412/contatos').then(function (response) {
                  $scope.contatos = response.data;
            }).catch(function(response, status){
                  $scope.message = "Erro: " + response.data;
            }); 
        }

        var carregarOperadoras = function() {
            $http.get('http://localhost:3412/operadoras').then(function (response) {
                $scope.operadoras = response.data;
            }); 
        }

        $scope.adicionarContato = function(contato) {
            contato.data = new Date();
            var config = {
                  headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                  }
            }
            $http.post("https://requestb.in/ped43xpe", contato, config).then(function successCallback(response) {
                console.log(contato);
                delete $scope.contato;
                $scope.controlForm.$setPristine();
            }); 
        };

        $scope.apagarContatos = function(contatos) {
            $scope.contatos = contatos.filter(function(contato) {
                if(!contato.selecionado) return contato;
            });
        };

        $scope.isContatoSelecionado = function (contatos) {
            return contatos.some(function (contato) {
                return contato.selecionado;
            });
        }

        $scope.ordernarPor = function (campo) {
            $scope.criterioDeOrdenacao = campo;
            $scope.direcaoDaOrdenacao = !$scope.direcaoDaOrdenacao;
        }

        carregarContatos();
        carregarOperadoras();
    });

On the console, this message appears:

TypeError: Cannot read property 'some' of undefined
at b.$scope.isContatoSelecionado (index_diretivas.html:78)
at fn (eval at compile (angular.js:15584), <anonymous>:4:259)
at m.$digest (angular.js:18276)
at m.$apply (angular.js:18553)
at angular.js:1942
at Object.invoke (angular.js:5079)
at c (angular.js:1940)
at Wc (angular.js:1960)
at we (angular.js:1845)
at angular.js:34115

Follow the body part of the page, where the controller is deployed:

<body ng-controller="ListaTelefonicaCtrl">
    <div class="jumbotron">

        <h3>{{app}}</h3>
        {{message}}
        <input class="form-control" type="text" ng-model="criterioDeBusca" placeholder="O que você estã procurando" />
        <table class="table">
            <tr>
                <th></th>
                <th><a href="" ng-click="ordernarPor('nome')"> Nome </a></th>
                <th><a href="" ng-click="ordernarPor('telefone')"> Telefone </a></th>
                <th>Operadora</th>
                <th>Data</th>
            </tr>
            <tr ng-class="{'selecionado negrito': contato.selecionado}" ng-repeat="contato in contatos | filter:criterioDeBusca | orderBy:criterioDeOrdenacao:direcaoDaOrdenacao">
                <td><input type="checkbox" ng-model="contato.selecionado" /></td>
                <td>{{contato.nome}}</td>
                <td>{{contato.telefone}}</td>
                <td>{{contato.operadora.nome | lowercase}}</td>
                <td>{{contato.data | date: 'dd/MM/yyyy HH:mm'}}</td>
                <td><div style="width: 20px; height: 20px;" ng-style="{'background-color': contato.cor}"></div></td>
            </tr>
        </table>
        <hr />

        <form name="controlForm">
            <input class="form-control" type="text" ng-model="contato.nome" name="nome" placeholder="Nome" ng-required="true" ng-minlength="10" />
            <input class="form-control" type="text" ng-model="contato.telefone" name="telefone" placeholder="Telefone" ng-required="true" ng-pattern="/^\d{4,5}-\d{4}$/" />
            <select class="form-control" ng-model="contato.operadora" ng-options="operadora.nome + ' ( ' + (operadora.preco | currency) + ' ) ' for operadora in operadoras | orderBy:'nome'">
                <option value="">Selecione uma Operadora</option>
            </select>
        </form>

        <button class="btn btn-primary btn-block" ng-click="adicionarContato(contato)" ng-disabled="controlForm.$invalid">Adicionar Contato</button>
        <button class="btn btn-danger btn-block" ng-click="apagarContatos(contatos)" ng-if="isContatoSelecionado(contatos)">Apagar Contato</button>
        <br />
        <!--{{7.4578 | number:9}}-->
        <br />
        <div ng-messages="controlForm.nome.$error" class="alert alert-danger">
            <div ng-message="required">
                Por favor, digite o nome.
            </div>

            <div ng-message="minlength">
                O tamanho mínimo do campo é de 10 caracteres.
            </div>

        </div>

        <div ng-messages="controlForm.telefone.$error" class="alert alert-danger">
            <div ng-message="required">
                Por favor, digite o telefone.
            </div>

            <div ng-message="pattern">
                O formato do telefone deve ser DDDDD-DDDD.
            </div>

        </div>

        <!-- <div ng-include="'footer.html'"></div> -->
        <div style="text-align: center;">
            Criado por Thiago Casotti
        </div>
    </div>
</body>
  • In your form I don’t see you using the method adicionarContato ! How are you calling him ? Provide a Minimum, Complete and Verifiable Example.

  • I call the method by means of a button. Follow: <button class="btn btn-Primary btn-block" ng-click="additionContact(contact)" ng-disabled="controlForm. $invalid">Add Contact</button>

  • Edith your question, put all necessary information!

  • I put the code in the question. This button is not inside the form.

  • I’m doing the test here, I return already.

  • This code you wrote ?

  • What contatos.some must contain / do ?

  • This code I picked up on a video lecture on angular JS.

  • some contacts identifies the selected contact in the list in order to delete it

  • Are you sure? Watch the video lesson again because it has the method $scope.apagarContatos that serves to erase the contact. I also don’t see where this calling the method $scope.isContatoSelecionado to generate the error, has another button ?

  • You have the delete contacts button, where the isContact method is called. I will put it in the question.

  • This code has a lot of errors, I voted to be closed, I recommend you watch the video lesson again, and see at what point it is missing or if the script is the same as the video.

Show 7 more comments

1 answer

0

Lack of information Headers

var config = {
  headers : {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
  }
}

See working

Here in the Sopt does not work the snippet, but you can see working on jsbin.com and see the data being received in requestbin

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http) {
  $scope.operadoras = [
    {
      nome: 'VIVO',
      preco: 1.5
    },
    {
      nome: 'CLARO',
      preco: 1.5
    },
    {
      nome: 'OI',
      preco: 1.5
    }
  ];
  $scope.adicionarContato = function(contato) {
    contato.data = new Date();
    var config = {
      headers : {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
      }
    }
    $http.post("https://requestb.in/ped43xpe", contato, config).then(function successCallback(response) {
      console.log(contato);
      delete $scope.contato;
      $scope.controlForm.$setPristine();
    }); 
  };
});
<div ng-app="myApp" ng-controller="formCtrl">
<form name="controlForm">
    <input class="form-control" type="text" ng-model="contato.nome" name="nome" placeholder="Nome" ng-required="true" ng-minlength="10" />
    <input class="form-control" type="text" ng-model="contato.telefone" name="telefone" placeholder="Telefone" ng-required="true" ng-pattern="/^\d{4,5}-\d{4}$/" />
    <select class="form-control" ng-model="contato.operadora" ng-options="operadora.nome + ' ( ' + (operadora.preco | currency) + ' ) ' for operadora in operadoras | orderBy:'nome'">
        <option value="">Selecione uma Operadora</option>
    </select>
</form>
  <button class="btn btn-primary btn-block" ng-click="adicionarContato(contato)" ng-disabled="controlForm.$invalid">Adicionar Contato</button>
</div>
  
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script>

Reference

  • I checked the test. But when I try to add the name, the error [Object Error] { ... } appears on the console.

  • Ask the question like this yours Controller, if possible take the console print and also put in the question.

  • No http://jsbin.com/jacivoyepi/edit?html,js,console,output error appears [Object Error] { ... }

  • You have implemented in your code ? This error is happening because of Cors, but if you see in requestbin he’s getting the data. At least for me it’s been stating that he’s getting all the attempts I’ve made.

  • Try http://jsbin.com/jacivoyepi/edit?console,output I saw that the example was wrong

  • It worked, but in https://requestb.in/151pkra1?inspect I can’t see the name sent.

  • It’s on the left side like this: {"nome":"Testando agora","telefone":"9999-9999","operadora":{"nome":"OI","preco":1.5},"data":"2017-11-30T01:23:03.627Z"}:

Show 2 more comments

Browser other questions tagged

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