0

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

asked Jan 10, 2015 at 10:32

4 Answers 4

2

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.
 });
answered Jan 10, 2015 at 10:46
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Jan 10, 2015 at 10:46

1 Comment

oooh, ok, I thought it's an invocation that's why I was expecting it to pass parameter, so it will pass response at invocation time and I won't have to pass it?
1

then function will call your callback with response (data, actually) object.

answered Jan 10, 2015 at 10:45

Comments

0

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.

answered Jan 10, 2015 at 10:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.