2
I’m having a little trouble understanding the workings of Promises of Angularjs. I have the following code:
function validateUser(name, pw) {
var status = '';
var data = {login: name, senha: pw, plataforma: 'APP'};
$http.post('http://localhost:8100/login', data)
.then(function(response) {
console.log(response.data.retorno);
var status = response.data.retorno;
}, function(err) {
console.log(err)
});
}
function teste(name, pw) {
var status = validateUser(nome, pw);
alert(status);
...
}
The code works perfectly. However I cannot return the answer of a $http.post
for another function. I can only get the answer of that precedent in .then(function(){ ... }
In jQuery we used the async: false
to solve this problem. There is something similar in Angularjs?
You could put this return value into a controller variable or pass it as a parameter to another function. A callback, for example.
– Hamurabi Araujo
It’s not a "problem", that’s how it works : ) Using synchronous requests (
async: false
in jquery) not recommended.– bfavaretto
but how would I make my test Function() wait for return? I tried to follow the angular documentation and use var deferred = $q. Defer(); but I was not successful!
– alan
What you want to do (really) with the data, other than Alert?
– bfavaretto
@bfavaretto: I have the validateUser() function in my services.js file and have the test() function inside my controller.js. I want to receive this feedback in my controller to redirect the user to some page (depending on the msm status). I think it would be nice to do this redirection within services.js
– alan
As I am starting to work with Angularjs now. Perhaps my logic is not correct. I’m not sure if I should use http.post inside services. Or change the logic completely and use it inside controller.js
– alan
It is recommended to keep the controller as clean as possible. This request logic can stay in the service and only receive controller calls to be handled in the view. I recommend reading the styleguide adopted by the community: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
– Hamurabi Araujo