如何使用 Angular 获取登录用户?

k88*_*074 2 http node.js express angularjs passport.js

也许我错过了一些非常微不足道的事情,但我找不到答案。

我正在为客户端实现一个基于 Nodejs、Express 和 Angular 的 Web 应用程序。我通过 Passport.js 处理我的注册和会话。因此,在服务器端,我可以通过request.user. 现在,我有一个登录用户,该用户进入其个人资料页面,通过角度视图显示。

问题是:现在为了向他们显示用户信息,我正在考虑$http向服务器发送请求,该服务器将用户从request显示的客户端发送回客户端。然而,这对我来说听起来很奇怪。

所以这是我的问题:有什么方法可以通过角度访问会话中的用户吗?如果是这样,客户端中实际存储了哪些用户信息?

提前致谢,如果这个问题太微不足道而无法提出,我们深表歉意:/

Hac*_*ese 5

您需要在 Angular 中创建一个服务来请求当前用户,并存储结果,以便您可以检索它以在控制器中使用。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;
           }
        };
   }]);
Run Code Online (Sandbox Code Playgroud)

该principal服务目前有一种方法,identity(). 该方法返回一个承诺。如果已检索到身份,它将立即使用该值进行解析。如果没有,它将尝试从 HTTP 端点获取它。如果 HTTP 调用成功,它将记录结果_identity并解决承诺。如果调用失败,则承诺将被拒绝。identity有二次用途。如果您为其提供单个参数,它将将该值设置为标识并且不返回任何内容。如果您已经拥有身份并希望立即设置(例如在成功登录后),这非常有用。

您可以像这样管理登录页面:

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
               });
     }
}]);
Run Code Online (Sandbox Code Playgroud)

其他地方需要当前身份的控制器可以执行如下操作:

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;
    });
}]);
Run Code Online (Sandbox Code Playgroud)

现在,您可以在登录后立即存储身份。我确实假设您登录用户的代码设置了一个 cookie 来表示身份验证令牌或登录端点中的任何内容。这样做的好处是,如果用户刷新浏览器,或者 cookie 存储一段时间,用户只需访问您的应用程序,身份就会自动使用该令牌 cookie 进行解析。

这个 plunk是一个更复杂的设置的工作演示。其中一些可能不适用于您(例如,它使用ui-router而不是常规路由),但它应该是一个合理的参考点。