Search code examples
angularjsjsonhttpangular-servicesangular-controller

Can we inject $http in to a Angular Service and pass that data to a controller?


I am trying to load JSON data from an external file using a service in AngularJS.

myApp.service('ContactsListService', function($http) {
    var contactsList = $http.get('js/contacts.json').success(function(data){
    return data;
    });
    console.log(contactsList); // prints some $http object 
    return {
    'contactsList': contactsList;
    };
}

myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
$scope.contacts = ContactsListService.contactsList;
console.log(ContactsListService.contactsList); // prints 'undefined' here
}]);

**JSON file:**

        [
          {
            name: 'Steph Curry',
            mobile: '111111111'
          },
          {
           name: 'Lebron James',
           mobile: '2323232323'
         }
     ]

I want to use the data from the service in the controller, I am unable pass that data. Correct me if I am injecting the service in an incorrect way.

Thanks!


Solution

  • You are storing the $http promise rather than the response from that ajax call. A better approach would be for the service to define a method that returned the promise, and for your controller to get that promise and use the result.

    myApp.service('ContactsListService', function($http) {
      this.getContactsList = function() {
        return $http.get('js/contacts.json');
      };
    });
    
    myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
      ContactsListService.getContactsList().success(function(data) {
        $scope.contacts = data;
      });
    }]);