1

In my main module I want to create a service that parses a json file and pushes the contents to an array, after I would like service to have the array be returned so it is easily accessible by any of the controllers. The issue is the function is running before the $http request is complete so it always returns an empty array

dashModule.factory('dataFetch', function($http) {
    var emailArray = [];

    $http.get('../data/emails.json').success(function log(obj) {
        for (var i = 0; i < obj.length; i++) {
            emailArray[i] = obj[i];
        }
    });

    return {
        test: function() {
            return emailArray;
        }
    };
});
Phil
  • 157,677
  • 23
  • 242
  • 245
Anfa A
  • 313
  • 2
  • 3
  • 9
  • You should try logging out the error using the .error(data, status, headers...). At first glance, this should work. So I think something is wrong with the way you are getting the json data, or the json data isn't available. – courtyen Jul 10 '15 at 03:16
  • if I console.log(obj) in my for loop it displays the correct json data, console.log(emailArray) in the for loop the array displays as it should. Only when it comes to return it bypasses the $http request – Anfa A Jul 10 '15 at 03:20
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Phil Jul 10 '15 at 03:21
  • @AnfaA you should try putting the return statement inside the success() method. – courtyen Jul 10 '15 at 03:27
  • @CourtneyNguyen you cant have a return within a method, the service fails when it doesn't return something – Anfa A Jul 10 '15 at 16:30

1 Answers1

4

use promise, like:

dashModule.factory('dataFetchService', function($http) {
    var myReq = function() {
        return $http.get('../data/emails.json').then(function(response){
            return response.data;
        });
    };
    return { myReq: myReq };
});

and

function getMyReq($scope, dataFetchService) {
    var myReqPromise = dataFetchService. myReq();
    myReqPromise.then(function(result) {        
        console.log(result);
    });
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162