I\'m having a lot of trouble with this and I can\'t seem to find anything here on SO or Google that helps me spot what I\'m doing wrong
//in $httpProvider.interceptors
if (typeof response.data === 'string') {
return response;
}
else {
return response.data;
}
Use defer:
obj.getResponse = function(){
var temp = {};
var defer = $q.defer();
$http.get('hello.php').success(function(data){
alert(data);
temp =data;
defer.resolve(data);
});
return defer.promise;
}
What's happening here is a result of the asynchronous nature of $http.get, When you run $http.get it doesn't run in order. That is, it 'branches off' and runs along side the rest of the code. This is done to accommodate for the server latency.
Here's a bad visualisation.
.getResponse Called Return Temp.
|-------------------|--------------|
|---------------------------------|
$http.get ~Waiting for Server~ Temp assigned to data.
Can you see how Temp is returned before it's been given a value?
Thankfully, you can use what Angular calls a promise, This is a variable which you can return from a function, that gets 'resolved' later. You instantiate a promise like this.
var myPromise = $q.defer();
You assign values to it by using
myPromise.resolve(data);
You can then return this promise later in the function, in the normal way. ie.
return myPromise.promise
Of course, for all of this you need the $q library, which you include in the function parameters.