Search code examples
angularjsgethttprequest

Capture the return of a method inside another method using AngularJS and $httprequest


I would like to have a question that must be simple. I need to capture the value of a variable to pass as a parameter (required) in order to consume an API. This variable is the return of a method that is a query inside a JSON file, but the return is given as undefined.

Follow the code:

Function to search the ID inside the JSON (with return)

self.getId = function(){   
$http({
        method: 'GET',
        url: self.urlEspecialidades,
        headers: { 'Content-Type': 'application/json' }
}).then(function(resposta) { 
var json = {};
json = resposta.data.data;  

for(var i = 0; i < json.length; i++){
    if(json[i].descricao == self.descricao){
        var id_especialidade = (json[i].id_especialidade); }
    }
    console.log(id_especialidade);
    return id_especialidade;
}) }

Function to search the state in JSON (with return):

self.getUf = function() {   
$http.get(self.urlEstados,
{
     transformResponse: function (cvt) {
     var x2js = new X2JS();
     var aposCvt = x2js.xml_str2json(cvt);
     return aposCvt; }        

}).then(function(resposta) { 
var json = {};
json = resposta.data.estados.data.item; 

for(var i = 0; i < json.length; i++){
    if(json[i].estado == self.estado){
        var uf = (json[i].uf);
         } 
    }
    console.log(uf);
    return uf;
}) }

Function to consume the API with the two parameters:

self.buscaPrestadores = function() {   
var id_parametro = self.getId();
var uf_parametro = self.getUf();

console.log(id);
console.log(uf);

$http({
        method: 'GET',
        url: self.urlPrestadores,
        headers: { 'Content-Type': 'application/json' },
        params: {uf:uf_parametro,id_especialidade:id_parametro}
}).then(function(resposta) { 
     //código vem aqui...
}) }

As you can see, the console finds the value inside the two functions, but when I try to capture them in the function that will consume the API, it shows as undefined, even though the return is declared. Can anyone tell me what I may be missing?

enter image description here


Solution

  • Add return before the promise, or you can't resolve anything

    self.getUf = function() {
      return $http.get(...).then(function(resposta) {
        ...
        return uf;
      })
    }

    This will return a Promise, not the value of uf.
    Once you write it as

    uf_parametro = self.getUf()
    

    you need to resolve uf_parametro as a Promise every time you need to extract the value of uf from it, e.g:

    uf_parametro.then(function(uf){ console.log(uf); })
    

    If you want to resolve both values at the same time, you need to use $q.all() method that takes an array of promises as the input:

    $q.all([id_parametro, uf_parametro]).then(function(res){ console.log(res); })