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?
I'm trying to call getCurrentUserInfo in the 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;
// });
// }
}])
-
did you include all the js files in your index.html page?Anonymous Duck– Anonymous Duck2016年03月09日 01:45:31 +00:00Commented Mar 9, 2016 at 1:45
-
1fdietz.github.io/recipes-with-angular-js/controllers/…Ranjith Kumar– Ranjith Kumar2016年03月09日 01:47:46 +00:00Commented Mar 9, 2016 at 1:47
1 Answer 1
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];
});
}
})
Then in your controller
AuthService.getCurrentUserInfo(whatEverYourParamsAre)
Edit: 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.