[英]Cannot access service from controller 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
無法修改,那么正確的方法是什么。
編輯:修復了問題中的復數錯字。 我的程序中沒有錯字,這是我在SO上打字時犯的一個錯誤。
在定義$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在該行應為單數形式而復數。
同樣,您正在使用服務服務,這是一個構造函數。 因此,您需要使用this關鍵字引用您的屬性。 角度服務方法使用new關鍵字在內部創建對象。 您可以嘗試工廠:
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
關鍵字,因為它不是構造函數。
希望這可以幫助!
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.