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.
1 Answer
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);
})
});
6 Comments
Susy11
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.
Omri Aharon
@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.Susy11
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?
Alexandre TRINDADE
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.
Susy11
Ok, thanks for the heads up. I moved my post inside my get, now it's working. Answer accepted
|
$rootScope.post_array = tempArray;Is tempArray as you expect?