0

I am using AngularJS to send form data to the server.

app.controller("OrganizerReg", ["$scope","$http", function($scope,$http) {


$scope.userOrganizer = {};


$scope.processform = function() {

    $http ({

            method: 'POST',
            url: 'http://52.11.67.77:3000/api/users',
            headers: {'Content-Type': 'application/json'},
            data: JSON.stringify($scope.userOrganizer)
    })
        .success(function(response) {
            console.log(response.user_id);
            $scope.user_id = response.user_id;
    })


    $http ({

        method: 'POST',
        url : 'http://52.11.67.77:3000/api/users/'+$scope.user_id+'/accessTokens',


    })
        .success(function(response) {

            console.log(response);
        })


}

In order to get access Token , I need to send a POST request.The response from first HTTP request , gives the user_id which is needed for generating the access token. The problem is whenever I send the request, the $scope.user_id returns undefined in the header. How to set my $scope.user_id global, so that it can be used by another HTTP request.

EDIT I read the duplicate question but it still hasn't helped me.

Community
  • 1
  • 1
shikhar
  • 174
  • 1
  • 11
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Alon Eitan Jan 29 '17 at 08:19
  • I read the answer before , but I still can't do it right. Can you help to solve this? – shikhar Jan 29 '17 at 08:25
  • @user5230591 use [this answer](http://stackoverflow.com/a/41919069/7484121), but be aware of your angular version – NonPolynomial Jan 29 '17 at 09:12

1 Answers1

5

use promise chains to call the request after another

function firstReq(){
    return $http({
        method: 'POST',
        url: 'http://52.11.67.77:3000/api/users',
        headers: {'Content-Type': 'application/json'},
        data: JSON.stringify($scope.userOrganizer)
    })
}

function secondReq(){
   return $http({
      method: 'POST',
      url : 'http://52.11.67.77:3000/api/users/' +$scope.user_id + '/accessTokens',
   })
}

$scope.processform = function() {
     firstReq()
       .then( function( response )
        {

            console.log(response.data.user_id);
            $scope.user_id = response.data.user_id;
            return secondReq();
        })
        .then(function(response){
           console.log(response.data);
        })


}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80