在 AngularJS 中,我的 Controller 如下:
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 不是函数
我缺少什么?
我读过这篇文章:Angular - TypeError: XX is not a function这看起来很相似,但我不明白。
最佳答案
您引用的答案(仅是我的),这与您希望实现的目标非常不同。
您的 $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'
}
}
});
});
关于javascript - AngularJS - XX 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325977/