I am trying to learn AngularJs and I have this code shown in the image below from a course am watching. the author is doing $http.get("url").then(function()... . What I don't understand is that onUserComplete function accepts response parameter, but in the then function, he's not passing this response parameter, and the example works. From what I understand in JavaScript is that we should do like: then(onUserComplete(response)) ; Can anyone exaplain it to me?
enter image description here
4 Answers 4
I suggest you go over the documentation again : https://docs.angularjs.org/api/ng/service/$http
but to make a long story short:
.then basically wait for the promise to return, that means the response from the server arrived.
the response include parameter data with the data from the server (let's say json)
then is excpect function as parameter so the function name is subsitute for the function, in your case it's onUserComplete.
Have a look on similar example:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Comments
The .then() function takes a callback function as it's parameter. The callback function is stored in the variable onUserComplete. So when the author writes .then(onUserComplete), onUserComplete is not being invoked, it's just being passed as a reference.
1 Comment
response at invocation time and I won't have to pass it?then function will call your callback with response (data, actually) object.
Comments
The .then expects a function as a parameter, which is exactly what onUserComplete is.
In a straightforward syntax, you would have seen:
.then(function (response) {
$scope.user = response.data;
});
And in a more common way, using anonymous syntax:
.then(response =>
$scope.user = response.data;
);
So that's all there is to it. The onUserComplete is just a substitute.