NewToJS NewToJS - 1 month ago 10
HTTP Question

Make an http request on a service, get response in controller

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");
});
};
});

Answer

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");
      });
  }
});