如何为AngularJS服务分配属性/方法

时间:2014-02-08 18:16:15

标签: javascript angularjs controller

我创建了一个角度服务:

app.service('myService', ['$http', '$q', function($http, $q){
    var getInfo = function(){
        return  $http({
            method: 'GET',
            url: 'X'
        });
    };
}]);

并且控制器无法识别它:

app.controller('myController', ['$scope', 'myService', function ($scope, myService) {


    myService.getInfo()
    .success(function(data, status, headers) {

    })
    .error(function(data, status, headers) {

    })

}]);

我在控制台中收到此错误:

TypeError: Object [object Object] has no method 'getInfo'

我缺少什么?

1 个答案:

答案 0 :(得分:3)

应该是this.getInfo,以便getInfo被指定为服务的方法。

app.service('myService', ['$http', '$q', function($http, $q){
    this.getInfo = function(){
        return  $http({
            method: 'GET',
            url: 'X'
        });
    };
}]);

以下是使用Angular创建服务的两个通用示例: Live demo (click).

app.service('myService', function() {
  // "this" is the service
  this.foo = function() {
    console.log('foo from myService1');
  };
});

使用工厂:

app.factory('myService2', function() {
  var myService2 = {
    foo: function() {
      console.log('foo from myService2');
    }
  };

  //what you return from a factory is the service
  return myService2;
});