How to return function correctly? (Scope of Variables)

3

I have the following function that performs a request to an API using the Angular and would like the function to return the data, but I'm having variable scope problems:

var buscarVagasPorEndereco = function(){
    var enderecosVagas = [];
    $http.get("dados.json").then(function(response){
        enderecosVagas = response.data.enderecosVagas;              
    });
    return enderecosVagas;
};
    
asked by anonymous 02.06.2017 / 21:58

2 answers

3

The% w / o of the Angular (and ajax in general) is asynchronous. This means that this function returns before ajax is done and therefore $http .

What you can do is return the promise and use the undefined thread to call the code that needs this response.

For example:

var buscarVagasPorEndereco = function(){
    return $http.get("dados.json").then(function(response){
        return response.data.enderecosVagas;              
    });
};

And then you can do:

buscarVagasPorEndereco().then(function(enderecosVagas){
    // fazer algo aqui com enderecosVagas
});
    
02.06.2017 / 22:11
0

Just put the return inside the get function:

var buscarVagasPorEndereco = function(){
    var enderecosVagas = [];
    $http.get("dados.json").then(function(response){
        enderecosVagas = response.data.enderecosVagas;   

        return enderecosVagas;
    });
};
    
02.06.2017 / 22:10