我试图从控制器中的服务调用一个函数,但是我得到一个错误,说我正在调用的东西不是函数.我是AngularJS的新手,所以我不确定我做错了什么.那么,在控制器中调用服务功能的正确方法是什么?
我正在尝试在ProfileCtrl中调用getCurrentUserInfo
.service('AuthService',function($http,Backand){ function getCurrentUserInfo() { return $http({ method: 'GET',url: baseUrl + "users",params: { filter: JSON.stringify([{ fieldName: "email",operator: "contains",value: self.currentUser.name }]) } }).then(function (response) { if (response.data && response.data.data && response.data.data.length == 1) return response.data.data[0]; }); } }) .controller('ProfileCtrl',['$scope','$ionicSideMenuDelegate','AuthService',function($scope,$ionicSideMenuDelegate,AuthService) { AuthService.getCurrentUserInfo().then(function(response){ $scope.user = response.data.data; }); // function getCurrentUserInfo() { // AuthService.getCurrentUserInfo() // .then(function (result) { // $scope.user = result.data; // }); // } }])
解决方法
你需要把它作为这个属性.
.service('AuthService',Backand){ this.getCurrentUserInfo = function() { return $http({ method: 'GET',params: { filter: JSON.stringify([{ fieldName: "email",value: self.currentUser.name }]) } }).then(function (response) { if (response.data && response.data.data && response.data.data.length == 1) return response.data.data[0]; }); } })
然后在你的控制器中
AuthService.getCurrentUserInfo(whatEverYourParamsAre)
编辑:其实,让我提供一些上下文. Angular将新函数应用于控制器中包含的每个.service(….).我们知道,在构造函数中调用this.aFunction会导致javascript中的new运算符将aFunction函数视为构造函数返回的对象的属性.