AngularJS服务无法正常工作 [英] AngularJS Service not working

查看:76
本文介绍了AngularJS服务无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发一个简单的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生成的promise,如下所示:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆