问题
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?
回答1:
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.
回答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;
})
});
回答3:
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;
})
});
回答4:
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.
来源:https://stackoverflow.com/questions/34090517/angularjs-service-not-working