AngularJS - XX不是一个功能

时间:2016-02-10 21:11:43

标签: javascript angularjs ngresource angularjs-resource

在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我错过了什么?

我已经阅读过这篇文章:Angular - TypeError: XX is not a function看起来很相似,但我不明白。

1 个答案:

答案 0 :(得分:3)

你引用的答案(仅限我的),这与你想要实现的完全不同。

你有不正确的$ 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'
      }
    }
  });
});