Error requesting Ajax (Get) AngularJS

2

I'm having a problem when I make a GET pro server request. My factory always returns an empty object, when it should not.

Then my server (localhost:8080/av1/listarCarroEstoque) whenever requested returns me the following JSON:

[
    {
        "id": 0,
        "chassi": "123455",
        "montadora": "ford",
        "modelo": "alto",
        "tipo": "HATCH_MEDIO_ESPORTIVO",
        "cor": "ROSA",
        "motorizacao": 2500,
        "preco": 599
    }
]

My file ListarCarroFactory.js :

app.factory('ListarCarroResource', ['$http', function($http) {

    return {
        listar: function() {
            var dados = {};

            $http.get('/av1/ListarCarroEstoque').
            success(function(data) {
                dados = data;
            }).
            error(function(error) {
                dados = error;
            });
            return dados;
        };
    }
}]);

My file ListarCarro.js :

app.controller('ListarVeiculo', function($scope, ListarCarroResource) {

    $scope.opcoes = ['carro', 'moto'];

    $scope.veiculoSelecionado = false;

    $scope.listarVeiculos = function() {
        if ($scope.veiculo == $scope.opcoes[0]) {
            console.log( (ListarCarroResource.listar()) );
            $scope.veiculoSelecionado = true;    
        } else {
            $scope.veiculoSelecionado = true;    
        }
    };
});

And my Main.js :

var app = angular.module('loja', ['ngResource']);
    
asked by anonymous 23.02.2015 / 03:25

1 answer

2

This happens because the $http.get call is asynchronous. That is, when it is called, it does not block processing until an API response is received. Therefore, even without the response received, the next lines of your code are executed and the dados variable is returned before the Ajax call completes.

You need to modify your code so that it is asynchronous. For example, instead of returning dados , return promise returned by call $http.get :

app.factory('ListarCarroResource', ['$http', function($http) {

    return {
        listar: function() {
            return $http.get('/av1/ListarCarroEstoque');
        };
    }
}]);

And in your controller:

app.controller('ListarVeiculo', function($scope, ListarCarroResource) {

    $scope.opcoes = ['carro', 'moto'];

    $scope.veiculoSelecionado = false;

    $scope.listarVeiculos = function() {
        if ($scope.veiculo == $scope.opcoes[0]) {
            ListarCarroResource.listar().success(function (dados) {
                console.log(dados);
            }).error(function () {
                alert("Erro!");
            });
            $scope.veiculoSelecionado = true;    
        } else {
            $scope.veiculoSelecionado = true;    
        }
    };
});
    
23.02.2015 / 04:27