Jenny Mok Jenny Mok - 20 days ago 8
AngularJS Question

return response.data value of $http in a function?

I try to call $http service within functions so I don't get nested callbacks. Without function scope it look like this:

$http.post('/verify_stripe_token', {email:$routeParams.email,token:$routeParams.t})
.then(function(response) {
console.log(response.data) // return 1
});


I want to use if(valid_token() == 1){} so I tried

function valid_token(){
$http.post('/verify_stripe_token', {email:$routeParams.email,token:$routeParams.t})
.then(function(response) {
return response.data;
});
}


Nothing worked? I do console.log(valid_token()) I got undefined.

Answer

First of all your valid_token() function doesn't return anything.

Next, you can't do if(valid_token() == 1) since $http requests are asynchronous

You would need to do something like:

function valid_token(){
  // return the promise
  return $http.post('/verify_stripe_token', {email:$routeParams.email,token:$routeParams.t})
  .then(function(response) {
    return response.data;
  });
}

valid_token().then(function(data){
  if(data == 1){
     // do what you need here
  }
})
Comments