0

I searched for my problem but could not find a solution. I want to be able to pass a variable initialized from an http.get to an http.post in angular. The problem is that my retur array is always empty. Here you can find my plnkr code with comments on what i want to achieve. Any ideea on how to make this work would be apreciated.

2
  • At this line: $rootScope.post_array = tempArray; Is tempArray as you expect? Commented Apr 24, 2014 at 10:14
  • Yes, inside the scope the array is ok. Commented Apr 24, 2014 at 11:00

1 Answer 1

1

In javascript, the calls are asynchronous. You must to call $http.post inside $http.get response:

$http.get('someurl').success(function (data) {
    var data_array = JSON.parse(data);
    var tempArray = new Array();
    tempArray['hi'] = 'hi';
    $rootScope.post_array = tempArray; 

    console.log($rootScope.post_array);
    $http.post('some-other-url',$rootScope.post_array).success(function(data){ 
        console.log(data);
    })    
});
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for the fast reply sir, but isn't this supposed to work out of the box? The $rootScope should be like a global js variable and it's initialized only on success, so my guess is that it should be visibile outside of the get method as well. Indeed moving the post into the get request should work but i would preffer another method.
@Susy11 Alexandre is correct. If you debug those lines you'll see that right after the $http.get(..) line you get straight to console.log($rootScope.post_array); without even reaching the server. If you want to assign this data to $rootScope you must wait for the request to return.
Noob question maybe: the success function does not mean that the request succeded? so that means that the rootScope is initialized after it has data right?
You're wrong. The success function means that your request succeed. In my code, when $http.get finish with success, your $rootScope.post_array will be assigned and you can access it in all your application. But you must to wait for the request to return. You must to understand that here we are dealing with asynchronous functions, that are not executed at the same time. In your code, the browser will execute $http.get and then $http.post will be executed BEFORE $http.get has been returned.
Ok, thanks for the heads up. I moved my post inside my get, now it's working. Answer accepted
|

Your Answer

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.