Error prompts Ajax(Get) Angularjs

Asked

Viewed 64 times

2

I’m having a problem when I make a GET request to the server. My Factory always returns an empty object, when it should not.

So mine server (localhost:8080/av1/listarCarroEstoque) upon request return 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 mine Main.js:

var app = angular.module('loja', ['ngResource']);
  • I didn’t understand what the error was, it always returns the same JSON ?? Here it wouldn’t be $http.get('/project/av1/Listinginventory'). ?

  • The problem is not very clear. Your service in localhost:8080/av1/listarCarroEstoque is returning a collection (marked by symbols [ and ]) containing an item (marked by { and }). What would be the expected result?

  • Sorry, I misspelled the server url is localhost:8080/av1/listCarroEstoque

  • When I call the list method from my Factory it returns me an empty object with no data inside, that’s the problem.

  • @Leonvillardoela I would suggest adding this last comment to the question then. Another thing - in the code present in the Pastebin there is no mention to the Resource Factory (mentioned in main.js, ngResource module').

  • I already changed thanks @Onosendai.

  • Make a fiddle said...

Show 2 more comments

1 answer

2

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

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

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

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

And on 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;    
        }
    };
});

Browser other questions tagged

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