简体   繁体   English

在AngularJS中的应用程序启动时初始化当前用户服务

[英]Initialize Current User Service on Application Start in AngularJS

I'm developing a Single Page Application with AngularJS. 我正在使用AngularJS开发单页应用程序。

When a user successfully logs in, a security token is stored in a cookie. 用户成功登录后,安全令牌将存储在cookie中。 Now, when he refreshes the page, the token will be sent to the backend, which returns a JSON object "currentUser" containing all the relevant information about the current user (as name, access-groups, profile picture, etc.). 现在,当他刷新页面时,令牌将被发送到后端,该后端将返回一个JSON对象“ currentUser”,其中包含有关当前用户的所有相关信息(例如名称,访问组,个人资料图片等)。

The problem is, this is an asynchronous process of course, so when the controller starts another operation, say, just alerting the user's name, this value will be undefined at that time. 问题是,这当然是异步过程,因此,当控制器启动另一个操作(例如,仅警告用户名)时,该值将在那时未定义。

Of course, I could set a timeout but is there a better solution? 当然,我可以设置超时时间,但是有更好的解决方案吗?

I thought about a "currentUserService", which initializes first (sending the cookie and filling the user information with the backend response) and can only be processed after this initialization is completed. 我想到了一个“ currentUserService”,它首先进行初始化(发送cookie并用后端响应填充用户信息),并且只能在初始化完成后才能进行处理。

But how can this be done? 但是,这怎么办呢? Or are there any other possibilities? 还是还有其他可能性?


edit: Hi guys, thanks for the input! 编辑:大家好,感谢您的输入!

Both of your suggestions seem to be very promising for asynchronous requests in general, but I think they might not fit perfectly for my concern: 通常,您的两个建议对于异步请求都非常有希望,但是我认为它们可能并不完全适合我的关注:

The information about the current user only have to be requested once , so I would like to store them for the whole application (eg in the rootScope or a service) accessible from any controller without having to request them again in every controller (as in the callback or resolve-solution) but make sure that there won't be any „timeout“ problems. 关于当前用户的信息只需要被请求一次 ,因此我想它们存储在可从任何控制器访问的整个应用程序中(例如,在rootScope或服务中),而不必在每个控制器中都再次请求它们(如回调或解决方案),但请确保不会出现任何“超时”问题。 Do you have any ideas? 你有什么想法?

If a user refreshes you have to initialize everything. 如果用户刷新,则必须初始化所有内容。 I assume the token is stored in localstorage or something and I assume this is angular 1.*. 我假设令牌存储在localstorage或其他东西中,并且我假设这是有角度的1. *。 To do this I think you should call user-related functions from your http call-callback: 为此,我认为您应该从http回调中调用与用户相关的功能:

  $scope.user = {};

  $scope.getUser = function(){
    $http({
       method: 'GET',
       url: '/someUrl'
    }).then(function (res) {

      $scope.user = res.data; //or whatever the response is
      $scope.handleUserRelatedThings();

    }).catch(function(err) {

      //handle error

    })

  }

  $scope.handleUserRelatedThings = function(){

   //do things with $scope.user
   alert($scope.user.name);

  }

  //on init
  $scope.getUser();

You can resolve the user's data before the view loads either with ng-route or ui-router : 您可以在视图加载之前使用ng-routeui-router解析用户的数据:

This example is written for ui-router : 这个例子是为ui-router编写的:

.state('profile', {
 url: '/profile',
 controller: 'profileCtrl as vm',
 resolve: {
  user: function(AuthService) {
   //Return a promise or an object to be resolved.
   return AuthService.getUserFromToken(); //Say this is asynchronous and returns a promise
  }
 }
});

//In controller:
.controller('profileCtrl', function(... , user) {
 //User data available here
 this.user = user;
});

Please note if any errors arise during the resolve stage the state will not be loaded so you'll have to take care of the errors! 请注意,如果在解决阶段出现任何错误,则不会加载该状态,因此您必须注意错误!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM