6

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;
//    });
//  }

}])
2

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.