AngularJS - XX 不是函数

AngularJS - XX is not a function

在AngularJS中我有控制器如下:

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) {

        });
    };
};

和服务工厂:

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

当我尝试在浏览器中使用注册功能时,我得到了 TypeError: UserService.register is not a function 我错过了什么?

我读过这个post: 看起来很相似,但我不明白。

您参考的答案(仅我的),与您想要实现的答案大不相同。

您的 $resource 对象格式不正确,自定义 $resource 方法应该存在于单个对象中,而不是将它们分开。

代码

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