Doubt ajax request with angular js

Asked

Viewed 817 times

0

Today when performing an ajax request for a url containing a json to store within an array, the vector value is only populated within the http method, and out of it from the error, I did 2 console.log the first works by following around an empty array, follows the code.

myApp.controller('PrincipalController', function($scope, $http) {

    $scope.dadosEmail = [];

    $http.get('/dados-email.json').success(function(retorno) {
         $scope.dadosEmail = retorno; 
         console.log($scope.dadosEmail);
    }).error(function(msg) {
        alert('Erro');    
    });

    console.log($scope.dadosEmail);

    $scope.ordenaPorNome = function() {
        $scope.dadosEmail.sort(function(a, b) {

            //Resolve o problema de letras maisculas e minusculas.
            a = a.toLowerCase();
            b = b.toLowerCase();

            if (a.nome > b.nome) {
                return 1;    
            }
            if (b.nome > a.nome) {
                return -1;   
            } 

            return 0;
        });    
    };
});

1 answer

2


You need to put all the code that depends on the result of the request inside the callback successful. At its current position, this code executes before the result is available, as the HTTP request is done asynchronously.

Your code so it should look like this:

myApp.controller('PrincipalController', function($scope, $http) {

    $scope.dadosEmail = [];

    $http.get('/dados-email.json').success(function(retorno) {
         $scope.dadosEmail = retorno; 

         $scope.ordenaPorNome = function() {
             $scope.dadosEmail.sort(function(a, b) {

                 //Resolve o problema de letras maisculas e minusculas.
                 a = a.toLowerCase();
                 b = b.toLowerCase();

                 if (a.nome > b.nome) {
                     return 1;    
                 }
                 if (b.nome > a.nome) {
                     return -1;   
                 } 

                 return 0;
             });    
         };
    }).error(function(msg) {
        alert('Erro');    
    });
});

As the function $scope.ordenaPorNome will only be set after the request response arrives, you also need to be careful not to call it before it exists.

  • I would have some way to avoid this problem without involving my function within my AJAX request?

  • The most you can do is call a function on success and pass to it the return. Within this other function you would define the ordenaPorNome. It’s the same thing in terms of execution flow, only changes the visual organization of the code.

  • I thought the code gets a little disorganized, but really you were right, thank you very much :)

  • As a matter of fact, so do I. I would not put everything inside the callback, create separate and chained functions, as I explained in the other comment. The code I posted was more to explain the same asynchronous execution flow. Maybe this will help you (although a little too theoretical): http://answall.com/questions/16950/comoreprogram%C3%A7%C3%A3o-ass%C3%Adncrona-funciona-em-javascript

Browser other questions tagged

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