0

I'm making an http request for a local JSON file using a Service. I'm trying to store the data from the successful HTTP request in my controller but that part is not working. The http request does however seem to be successful on the Service.

var myModule = angular.module("MyApp", [])

  .controller('MyController', function(Utilities){

     //this is not working
     self.socialArr = Utilities.getData("data.json");

   }).service('Utilities', function($http) {

     var self = this;

     self.getData = function(jsonData) {
       $http.get(jsonData)
        .then(function(response) {
            //First function handles success
            var theData = response.data;
            console.log(theData); //this works (data is logged)
            return theData;
        }, function(response) {
            //Second function handles error
            console.log("Error loading JSON data");
        });
     };
 });
Rob
  • 14,746
  • 28
  • 47
  • 65
NewToJS
  • 2,011
  • 4
  • 35
  • 62

4 Answers4

4

You aren't returning anything from the service method. Return the $http promise and use then() in controller to assign the returned data to controller property. Also you haven't defined self in controller

angular.module("MyApp", [])

.controller('MyController', function(Utilities) {
  // store reference of "this"
  var self = this;
  // call service method
  Utilities.getData("data.json").then(function(data) {
    // assign data after promise resolves
    self.socialArr = data;
  });


}).service('Utilities', function($http) {

  var self = this;

  self.getData = function(jsonData) {
    // return the promise
    return $http.get(jsonData).then(function(response) { 
        return response.data;
      }, function(response) {
        //Second function handles error
        console.log("Error loading JSON data");
      });
  }
});
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

I think You should be using a promise.because you are making an asyncronous call.

 self.getData = function(jsonData) {
var deferred = $q.defer();
       $http.get(jsonData)
        .then(function(response) {

            if (response.data) {
      deferred.resolve(response);
    } else {
      deferred.reject(response);
    }

        }, function(response) {
            deferred.reject(response);
        });
 return deferred.promise;
     };

then in the controller

 Utilities.getData("data.json").then(function(res)
{
   self.socialArr=res;
},function(e){

});
saiyan
  • 512
  • 6
  • 21
  • 2
    Using `$q` is [an anti-pattern](http://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) when `$http` already returns a promise – charlietfl Oct 23 '16 at 15:29
  • No I creating a custom promise to http returned promise this way It will work. – saiyan Oct 23 '16 at 15:42
  • No I creating a custom promise to http returned promise this way It will work.For your approach of using a function to make an http call the above answer works or make http call with its promise inline.see: http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/ **What about post processing** section – saiyan Oct 23 '16 at 15:48
  • You can post process in `then()` of `$http` with no problem. You would only need `$q` if other promises needed to be combined but that is over complicating what is when in question – charlietfl Oct 23 '16 at 16:09
0

You should return a promise after the $http.get().then(successCallback);

The return statement,

 return theData;

in your code is confined and "scoped" to the the successCallback. So in order to get a handle to it, you need to return the promise associated that the successCallback is part of.

         self.getData = function(jsonData) {

         // store the promise
         var promise = $http.get(jsonData)
        .then(function(response) {
            //First function handles success
            var theData = response.data;
            console.log(theData); //this works (data is logged)
            return theData;
        });

        // return the promise, which can get you the successCallback's    returned data.
        return promise;
      };        

The console.log output means the code executed, but the returned theData is no use without the promise it associated with.

In the controller:

          Utilities.getData("data.json").then(function(socialArr){
            $scope.socialArr = socialArr;
            // this should print
            console.log($scope.socialArr);
          });

A working plunkr here

Mahesh
  • 954
  • 8
  • 18
0
var myModule = angular.module("MyApp", [])

.controller('MyController', function(Utilities){

     Utilities.getData("data.json").success(function(responce) {
         self.socialArr = response.data;
     })

 })
.service('Utilities', function($http) {

    var self = this;

    self.getData = function(jsonData) {
       return $http.get(jsonData).error(function(responce) {
           console.log("error!");
       })
    };
});