Reputation: 2237
I'm trying to perform a GET request to my API endpoint, which returns a JSON response. How do I do this?
Controller.js
oknok.controller('listagemController', function ($scope, $http) {
$scope.init = function () {
$http.get("/api/veiculos")
.then(function (data) {
alert(data.toJSON());
}).catch(function (error) {
alert("Erro ao obter dados!");
});
}
});
Response from API when I execute curl in terminal
curl http://localhost:8181/api/veiculos
{
"_links" : {
"self" : {
"href" : "http://localhost:8181/api/veiculos"
}
},
"_embedded" : {
"veiculos" : [ {
"nome" : "daniela",
"tipo" : "tipo",
"_links" : {
"self" : {
"href" : "http://localhost:8181/api/veiculos/559d59b1ccf2ebb2fc97e70e"
},
"contatos" : {
"href" : "http://localhost:8181/api/veiculos/559d59b1ccf2ebb2fc97e70e/contatos"
},
"clientes" : {
"href" : "http://localhost:8181/api/veiculos/559d59b1ccf2ebb2fc97e70e/clientes"
}
}
} ]
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
Upvotes: 0
Views: 65
Reputation: 21901
I think you getting the data successfully but seems like there is some exception when you tring to alert is.
use JSON.stringify(data)
instead of data.toJSON()
$scope.init = function () {
$http.get("/api/veiculos")
.then(function (data) {
alert(JSON.stringify(data));
}).catch(function (error) {
alert("Erro ao obter dados!");
});
}
How do I get "nome" and "tipo" from veículo?
// get the _embedded property of the object (data)
var embedded = data._embedded;
//get the veiculos property of the embedded object
var veiculos = embedded.veiculos;
//get the nome & tipo (veiculos is a array so you need to refer the first index to do that use veiculos[0])
var nome = veiculos[0].nome;
var tipo = veiculos[0].tipo;
Upvotes: 1
Reputation: 7490
Yo can't use alert in that way but you can use console.log instead.
oknok.controller('listagemController', function ($scope, $http) {
$scope.init = function () {
$http.get("/api/veiculos")
.then(function (data) {
console.log(data.toJSON());
}).catch(function (error) {
console.log("Erro ao obter dados!");
});
}
});
Upvotes: 0
Reputation: 28318
Try this:
oknok.controller('listagemController', function ($scope, $http) {
$scope.init = function () {
$http.get("/api/veiculos")
.then(function (data) {
alert(data.toJSON());
}).catch(function (error) {
alert("Erro ao obter dados!");
});
}
});
You need to use .then
and .catch
instead of .success
and .error
.
Upvotes: 1