也许我错过了一些非常微不足道的东西,但我找不到答案。
我正在为客户端实现一个基于 Nodejs、express 和 Angular 的 Web 应用程序。
我通过 Passport.js 处理我的注册和 session 。因此,在服务器端,我可以通过 request.user
访问登录的用户。
现在,我有一个登录用户,该用户进入其个人资料页面,通过 Angular View 显示。
问题是:为了向他们显示用户信息,我现在正在考虑向服务器发送一个 $http
请求,该请求将用户从 request
中获取并将其发送回显示它的客户端。然而,这对我来说听起来很奇怪。
所以这是我的问题:有没有办法通过 Angular 访问 session 中的用户?如果是这样,客户端中实际存储了哪些用户信息?
提前致谢,如果问题太微不足道而无法提出,我们深表歉意:/
最佳答案
您需要在 Angular 中创建一个服务来请求当前用户,并存储结果,以便您可以检索它以在 Controller 中使用。 Angular 中没有为此构建任何东西;你必须自己创建它。然而,它相当简单。
myapp // assume was previously defined using var myapp = angular.module('myapp', []);
.factory('principal', ['$http', '$q', function($http, $q) {
var _identity = undefined;
return {
// this function returns the current _identity if defined; otherwise, it retrieves it from the HTTP endpoint
identity: function(setIdentity) {
if (setIdentity) {
_identity = setIdentity;
return;
}
var deferred = $q.defer();
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
$http.get('/path/to/endpoint')
.success(function(result) {
_identity = result;
deferred.resolve(_identity);
})
.error(function() {
_identity = undefined;
deferred.reject();
});
return deferred.promise;
}
};
}]);
此主要
服务目前只有一个方法,identity()
。该方法返回一个 promise 。如果已检索到身份,它将立即使用该值进行解析。如果没有,它将尝试从 HTTP 端点获取它。如果 HTTP 调用成功,它会将结果存储到 _identity
中并解析 promise 。如果调用失败,则 promise 将被拒绝。 身份
还有次要用途。如果您为其提供单个参数,它将将该值设置为标识并且不返回任何内容。如果您已经拥有身份并希望立即设置(例如在成功登录后),这非常有用。
您可以像这样管理登录页面:
myapp.controller('SignInCtrl', ['$scope', 'principal', '$http', function($scope, principal, $http) {
// these two values will be bound to textboxes in the view
$scope.username = '';
$scope.password = '';
// this function will be called when the sign in form is submitted
$scope.submit = function() {
$http.post('/path/to/signin', {username: $scope.username, password: $scope.password })
.success(function(identity) {
// assumes /path/to/signin returns a JSON representation of the signed-in user upon successful authentication
// presumably the endpoint also sets a cookie representing an auth token or something of that nature. the browser will store this automatically for you
principal.identity(identity); // set the identity immediately
// do whatever else on successful login, like redirect to another route
});
}
}]);
其他地方需要当前身份的 Controller 可以执行如下操作:
myapp.controller('MyCtrl', ['$scope', 'principal', function($scope, principal) {
// retrieve the identity. when it resolves, set user on the scope
principal.identity().then(function(identity) {
// after this, you can use user in your view or later in your controller
$scope.user = identity;
});
}]);
现在您可以在登录后立即存储身份。我确实假设您登录用户的代码设置了一个 cookie 来表示身份验证 token 或登录端点中的任何内容。这样做的好处是,如果用户刷新浏览器,或者 cookie 存储一段时间,用户只需访问您的应用程序,身份就会自动使用该 token cookie 进行解析。
This plunk是一个更复杂的设置的工作演示。其中一些可能不适用于您(例如,它使用 ui-router
而不是常规路由),但它应该是一个合理的引用点。
关于angularjs - 如何使用 Angular 获取登录用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24843339/