javascriptangularjsngresourceangularjs-resource

AngularJS - XX is not a function


In AngularJS I have Controller as follows:

function LoginController($scope, $rootScope, $location, $cookieStore, UserService) {

    $scope.rememberMe = false;

    $scope.login = function() {
        UserService.authenticate($.param({
            username: $scope.username,
            password: $scope.password
        }), function(authenticationResult) {
            var authToken = authenticationResult.token;
            $rootScope.authToken = authToken;
            if ($scope.rememberMe) {
                $cookieStore.put('authToken', authToken);
            }
            UserService.get(function(user) {
                $rootScope.user = user;
                $location.path("/");
            });
        });
    };

    $scope.register = function() {
        UserService.register($.param({
            username: $scope.username,
            password: $scope.password
        }), function(authenticationResult) {

        });
    };
};

And service factory:

var services = angular.module('exampleApp.services', ['ngResource']);

services.factory('UserService', function($resource) {
    return $resource('rest/user/:action', {}, {
        authenticate: {
            method: 'POST',
            params: {
                'action': 'authenticate'
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
    }, {
        register: {
            method: 'POST',
            params: {
                'action': 'register'
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
    });
});

When I'm trying to reach register function in browser I am getting TypeError: UserService.register is not a function What I am missing?

I've read this post: Angular - TypeError: XX is not a function which seems similar, but I don't understand it.


Solution

  • The answer which you are referenced(it mine only), which is very different than what you are looking to achieve.

    You have incorrect $resource object format, custom $resource method should be there in single object rather than having them separate.

    Code

    services.factory('UserService', function($resource) {
      return $resource('rest/user/:action', {}, {
        authenticate: {
          method: 'POST',
          params: {
            'action': 'authenticate'
          },
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        },
        register: {
          method: 'POST',
          params: {
            'action': 'register'
          },
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }
      });
    });