I'm trying to use $http, but why it return null result?
angular.module('myApp')
.factory('sender', function($http) {
var newData = null;
$http.get('test.html')
.success(function(data) {
newData = data;
console.log(newData)
})
.error(function() {
newData = 'error';
});
console.log(newData)
return newData
})
Console say: http://screencast.com/t/vBGkl2sThBd4. Why my newData first is null and then is defined? How to do it correctly?
This JavaScript code is asynchronous.
Is executed before what inside
success
So at first time, the newData is null (you set it to be null)
And when the http response is returned (inside the success), the newData gets its new value.
This is very common in Javascript, you should do all your work inside the
success
.As YardenST said,
$http
is asynchronous so you need to make sure that all functions or display logic that are dependent on the data that is returned by your$http.get()
, gets handle accordingly. One way to accomplish this is to make use of the "promise" that$http
returns:Plunkr Demo