AngularJS 服务不工作 [英] AngularJS Service not working
问题描述
我一直在开发一个简单的 AngularJS 应用程序.我需要为它实现一个名为countryservice"的自定义服务.以下是我的代码.
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?
推荐答案
getallcountries
服务方法应该像这样返回 $http.get
生成的承诺:>
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;
});
});
另外,请注意您不必向控制器注入 $http
服务.
Also, notice that you don't have to inject $http
service to the controller.
这篇关于AngularJS 服务不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!