I've encountered an issue while attempting to retrieve a JSON from an API using XMLHttpRequest within a factory. Despite the debug logs suggesting that everything is functioning correctly, I keep getting an "undefined" response.
Below is the code for my factory:
.factory('MyService', function(){
return {
getJSON: function(path){
var xhr = new XMLHttpRequest();
xhr.open("Get", path, true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
console.log(JSON.parse(xhr.responseText)); // Correct JSON object is displayed
return JSON.parse(xhr.responseText); // Returns the same object
}else{
return xhr;
}
}
};
xhr.send();
}
}
})
Here's how I'm calling the service in my controller:
$scope.test = MyService.getJSON("api url"); // Always returns undefined
Although the console log inside the factory indicates that the JSON is retrieved successfully, the $scope.test remains undefined even after returning the JSON object.
If anyone has insights on why this behavior is happening, your input would be greatly appreciated. Thank you!