无法从控制器AngularJS访问服务



我正在从事一个角度项目,在那里我正在为较旧的项目添加新功能。
我正在尝试向控制器注册服务,但是在我的控制器无法找到服务中的功能的情况下会遇到错误。

这是我的控制器的定义方式(我知道这不是标准方式,但是我必须遵循此操作。)

angular.module("test").controller("listCtrl", listCtrl);
listCtrl.$inject = ["$scope", "$state", "$timeout", "listService", "$rootScope"];
function listCtrl($scope, $state, $timeout, listService, $rootScope ) {
  this.$scope= $scope;
  $scope.service=listService;
  //some other definitions
  $scope.items = $scope.service.getPage(%function_ARGUMENTS%);
}

这是定义服务的方式:

angular.module("test").service("listService", listService);
listService.$inject = ['$state', '$rootScope'];
function listService($state, $rootScope) {
   function getPage(%function_ARGUMENTS%) {
     //getPage function definition goes here
   }
}  

现在,由于某种原因,我得到了错误:

无法读取未定义的属性'getPage'

我无法弄清楚可能导致的。
$scope如何定义的问题?如果是,那么假设this.$scope=$scope无法修改。

是什么正确的方法。

编辑:在问题中修复了复数错字。我的程序中没有错字,这是我在打字时犯的一个错误。

预期错误,因为您已经定义了 $scope.service,其中使用 $scope.services注意额外的" s"。因此,请使用正确的变量

$scope.items = $scope.service.getPage(%function_ARGUMENTS%);

但是,您将直到与返回服务对象关联的函数getPage收到另一个错误。

function listService($state, $rootScope) {
   this.getPage = function() {
     //getPage function definition goes here
   }
}  

或,

function listService($state, $rootScope) {
   function getPage () {
     //getPage function definition goes here
   }
   this.getPage = getPage;
}  
angular.module("test").factory("listService", listService);
listService.$inject = ['$state', '$rootScope'];    
function listService($state, $rootScope) {
   return {
      function getPage(%function_ARGUMENTS%) {
         //getPage function definition goes here
      }
   }
}

只需在您的服务功能时写上述。

我也注意到:$ scope.items = $ scope.services.getPage(%function_arguments%);

应该是:$ scope.items = $ scope.service.getPage(%function_arguments%);

$ scope.Service在该线上应该是奇异的。

也是您使用的服务服务,这是构造函数函数。因此,您需要使用此关键字引用您的属性。Angular Service方法使用新关键字在内部创建对象。您可以尝试工厂:

angular.module("test")
  .factory("listService", listService);
  listService.$inject = ['$state', '$rootScope'];
  function listService($state, $rootScope) {
    function getPage(%function_ARGUMENTS%) {
      //getPage function definition goes here
    }
    return {
      getPage: getPage
    };
 }

这与您所拥有的更相似,并且您不需要使用this关键字,因为它不是构造函数函数。

希望这会有所帮助!

欢呼

最新更新