I need to make requests, however the first must be GET
(getByName) and then execute the rest because they depend on it. It turns out that my code is sending an undefined as the requests depend on the contactsUri that is defined in this first GET request.
By order of alerts, the success of the request get last and the other requests are made. How do I make a "synchronous request" to ensure that only after running getByName will perform the rest?
$scope.salvar = function () {
alert("Buscando uri de agencia....");
var contatosUri = [];
for(var j = 0; j < $scope.contatos.length; j++){
var nomeAgencia = $scope.contatos[j].agencia;
agenciasAPI.getByNome(nomeAgencia).success(function (data){
alert("Inserir no array.. " + data._links.self.href);
contatosUri.push(data._links.self.href);
}).catch(function (error){
alert(JSON.stringify(error) + "\t" + error);
});
}
alert("Foi inserido no array...." + contatosUri[0]);
alert("Requests de veiculo...");
//BUSCAR URI DE AGENCIA
function buscarAgenciaUri(vetorDados) {
try {
var agenciasUri = [];
for (var i = 0; i < $scope.listaAgencias.length; i++) {
var json = $scope.listaAgencias[i];
for (var k = 0; k < vetorDados.length; k++) {
if (json.nome == vetorDados[k]) {
agenciasUri.push(json._links.self.href);
}
}
}
} catch (err) {
alert(err);
}
return agenciasUri;
}
var agenciasSeparadas = $scope.opcoes + '';
agenciasSeparadas = agenciasSeparadas.split(',');
var agenciasUri = buscarAgenciaUri(agenciasSeparadas);
//ENVIAR DADOS DE VEICULO
var jsonObj = {
nome: $scope.nome,
tipo: $scope.tipo,
agencias: agenciasUri,
contatos: contatosUri
};
alert("Enviar json de veiculo..." +JSON.stringify(jsonObj));
veiculosAPI.postVeiculo(jsonObj)
.success(function (data, status, headers, config) {
$scope.nome = null;
$scope.tipo = null;
}).error(function (data, status, headers) {
alert("Erro ao salvar dados do veiculo!");
alert(data + "\t" + JSON.stringify(data));
});
};