Doubt with $http in Angularjs

Asked

Viewed 71 times

2

When I do the get, I load it into an object the $Scope.contacts and can show it in my View of html.

However, I can only access it within my function of then(function(){}), when I leave the part where I called $http, I can no longer access $Scope.contacts, where it is listed as $http Undefined.

I analyzed that even creating a global variable, if I associate its value to $Scope.contacts inside my $http I can’t access the value of the variable either, which will also appear as Undefined.

<script type="text/javascript">

    var app = angular.module("myApp",[]);

    app.controller("myCtrl",function($scope,$http){

        $scope.contatos = [];
        $scope.nomes = [];
        var st;

        $http.get("/jsons/contatos.json").then(function(response) {

            console.log("sucesso");
            $scope.contatos = response.data.contatos;
            st = $scope.contatos;

            for(j = 0; j < $scope.contatos.length; j++){
                angular.forEach($scope.contatos[j], function(value,key){                    
                    if(key=="nome"){
                        $scope.nomes.push(value);
                    }                   
                });
            }               
        },function(response){
            console.log("erro");
        });

        console.log($scope.contatos);//aqui ele ja não funciona mais
        console.log(st);//não funciona tambem

    });
</script>

  • Like $http.get is asynchronous, probably when arriving at the code after it (Console.log...) not yet have the return. So your code (Console.log...) may be running before the return of the $http.get and so print undefined.

  • Mr Renan, thank you very much for your reply.

  • Okay @Nicholas Maestrello Agiz I’ll put an answer then.

1 answer

1


As the method $http.get is asynchronous when executing lines of code console.log($scope.contatos); and console.log(st); the method $http.get hasn’t returned yet, so print Undefined.

Browser other questions tagged

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