Harry Berry Harry Berry - 3 months ago 10
AngularJS Question

Store AJAX result in factory and retrieve in controller

I am currently trying to store a $http JSON request to a variable in a factory and then retrieve the value of that variable in a controller.

Currently all I receive back is undefined. I imagine the AJAX request isn't finished running before the function gets called. I am new to Angular so trying to grab any basic concepts I can and helpful knowledge.

app.factory('typiCode', function($http) {
var jsonService = {
async: function() {
var promise = $http.get('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
console.log(response);
return response.data;
})
return promise;
}
};
return jsonService;
});



app.controller("getJson", function($scope, typiCode) {
$scope.returnedData = typiCode.jsonService;
$scope.logResults = function() {
var theData = $scope.returnedData;
console.log(theData);
}
});

<button ng-click="logResults()">Launch data</button>


Thank you in advance!

Answer

Your typiCode factory returns your jsonService object. So you should be calling typiCode.async() somewhere in your code.

You could do, for example, like this in your controller:

app.controller("getJson", function($scope, typiCode) {

    typiCode.async()
    .then(function(data) {
        $scope.returnedData = data;
    })

    $scope.logResults = function() {
        var theData = $scope.returnedData;
        console.log(theData);
    }
});