如何使用AngularJS在控制器中调用服务函数? [英] How to call service function in a controller with AngularJS?
问题描述
我正在尝试从控制器中的服务调用函数,但收到一条错误消息,说我正在调用的东西不是函数.我是AngularJS的新手,所以我不确定自己在做什么错.那么,在控制器中调用服务函数的正确方法是什么?
I'm trying to call a function from a service in a controller but I get an error saying that the thing I'm calling isn't a function. I'm new to AngularJS so I'm not exactly sure what I'm doing wrong. So, what's the correct way to call a service function in a controller?
我正在尝试在ProfileCtrl
.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;
// });
// }
}])
推荐答案
您需要将其设置为this
的属性.
You need to make it a property of this
.
.service('AuthService', function($http, Backand){
this.getCurrentUserInfo = function() {
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];
});
}
})
然后在您的控制器中
AuthService.getCurrentUserInfo(whatEverYourParamsAre)
实际上,让我提供一些背景信息. Angular将new
函数应用于您包含在控制器中的每个.service(....)
.众所周知,在构造函数中调用this.aFunction会导致javascript中的new
运算符将aFunction
函数视为构造函数返回的对象的属性.
Actually, let me provide a little bit of context. Angular applies the new
function to every .service(....)
you include in your controller. As we know, calling this.aFunction in a constructor function causes the new
operator in javascript to treat the aFunction
function as a property on the object your constructor returns.
这篇关于如何使用AngularJS在控制器中调用服务函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!