2

I have been developing a simple AngularJS App. I need to implement a custom service named 'countryservice' for it. Following is my code.

var countryApp = angular.module('countryApp', []);

countryApp.service('countryservice', function ($http) {
this.getallcountries = function ($http) {
    $http.get('js/countries.json').success(function (data) {
        return data;
    });
}
});

countryApp.controller('CountryCtrl', function ($http, $scope, countryservice) {
$scope.countries = countryservice.getallcountries($http);
});

Unfortunately this code doesn't work for some reason. But cannot figure out why. When I do the same thing without creating my own custom service it works fine. Following is the code without implementing a custom service. This one works fine.

var countryApp = angular.module('countryApp', []);

  countryApp.controller('CountryCtrl', function ($scope, $http) {
  $http.get('js/countries.json').success(function (data) {
    $scope.countries = data;
  });
});

Can anybody help me with what I'm doing wrong with my custom service?

Gianmarco
  • 2,536
  • 25
  • 57
Jake
  • 477
  • 2
  • 12
  • 26

4 Answers4

4

The getallcountries service method should return the promise generated by $http.get like this:

var countryApp = angular.module('countryApp', []);

countryApp.service('countryservice', function ($http) {
this.getallcountries = function () {
    return $http.get('js/countries.json');
}
});

countryApp.controller('CountryCtrl', function ($scope, countryservice) {
   countryservice.getallcountries().success(function(data) {
      $scope.countries = data;
   });
});

Also, notice that you don't have to inject $http service to the controller.

kulak
  • 852
  • 7
  • 16
2

Try should try this:

countryApp.service('countryservice', function ($http) {
this.getallcountries = function () {
    return $http.get('js/countries.json');
}
});    

in controller:

countryApp.controller('CountryCtrl', function ($scope, countryservice) {
    countryservice.getallcountries().then(function(resp) {
        $scope.countries = resp.data;
    })
});
yukuan
  • 521
  • 5
  • 18
1

try with a return before $http

countryApp.service('countryservice', function ($http) {
    this.getallcountries = function ($http) {
        return $http.get('js/countries.json').success(function (data) {
            return data;
        });
    }
});

and a then in controller

countryApp.controller('CountryCtrl', function ($scope, countryservice) {
    countryservice.getallcountries().then(function(resp) {
        $scope.countries = resp.data;
    })
});
AlainIb
  • 4,544
  • 4
  • 38
  • 64
0
countryApp.service('countryservice', function ($http) {

var service = {};
service.getallcountries = function ($http) {
    var response;
    $http.get('js/countries.json').success(function (data) {
        response = data;
    });
    return response;
}

return service;
});

This is something similar at what I would do.

Gianmarco
  • 2,536
  • 25
  • 57