user3305480
user3305480

Reputation: 5

How to wait $http complete in AngularJS?

I have a problem about $http in Angularjs. I'm building system register step by step, I need to call $http to Facebook and receive result returned from Facebook at step one, so if there are error, this error is shown at step two. I want that this error will be shown at step one. I use Angularjs with Coffeescript!

### step one ###
#check username
if $scope.username == ""
    $scope.errorMessage.push "please enter username"
$http(
  method: "GET"
  url: "https://graph.facebook.com/" + identifier
).success((data, status, headers, config) ->
    ... do something...
).error((data, status, headers, config) ->
    ... if there is error
    $scope.errorMessage.push "error"
# break if has errors
if $scope.errorMessage.length > 0
    $scope.scrollTo("back-to-top")
    return false
# if everthing ok -> continue next step
return true

### step two ####
...do something...

Upvotes: 0

Views: 138

Answers (2)

Vaibhav Pachauri
Vaibhav Pachauri

Reputation: 2671

There is a concept of 'promises' which is being returned by $http service in angularjs. I would recommend that you explore the 'promises' from here and other blogs online.

You can use it as follows :

$http.get('https://api.xyz.com/users/abc/gists')
.then(function(response) {
  $scope.gists = response.data;
});

Upvotes: 1

Cristobal
Cristobal

Reputation: 61

Take a look at the $http response structure:

$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.
  });

As you can see it uses a callback structure, I think rechecking the $http documentation will be helpful for you.

Upvotes: 0

Related Questions