如何在 AngularJS 中存储当前用户上下文? [英] How do I store a current user context in AngularJS?

查看:23
本文介绍了如何在 AngularJS 中存储当前用户上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 AuthService,它登录一个用户,它返回一个用户 json 对象.我想要做的是设置该对象并在应用程序中反映所有更改(登录/注销状态),而无需刷新页面.

I have an AuthService, which logs in a user, it returns back a user json object. What I want to do is set that object and have all the changes reflected across the application (logged in/logged out state) without having to refresh the page.

我将如何使用 AngularJS 完成此任务?

How would I accomplish this with AngularJS?

推荐答案

完成此任务的最简单方法是使用服务.例如:

The easiest way to accomplish this is by using a service. For example:

app.factory( 'AuthService', function() {
  var currentUser;

  return {
    login: function() { ... },
    logout: function() { ... },
    isLoggedIn: function() { ... },
    currentUser: function() { return currentUser; }
    ...
  };
});

然后您可以在任何控制器中引用它.以下代码监视来自服务的值的更改(通过调用指定的函数),然后将更改的值同步到范围.

You can then reference this in any of your controllers. The following code watches for changes in a value from the service (by calling the function specified) and then syncs the changed values to the scope.

app.controller( 'MainCtrl', function( $scope, AuthService ) {
  $scope.$watch( AuthService.isLoggedIn, function ( isLoggedIn ) {
    $scope.isLoggedIn = isLoggedIn;
    $scope.currentUser = AuthService.currentUser();
  });
});

然后,当然,您可以使用您认为合适的信息;例如在指令、模板等中.您可以在菜单控制器等中重复此操作(根据您需要执行的操作进行自定义).当您更改服务状态时,所有这些都会自动更新.

And then, of course, you can use that information however you see fit; e.g. in directives, in templates, etc. You can repeat this (customized to what you need to do) in your menu controllers, etc. It will all be updated automatically when you change the state on the service.

更具体的内容取决于您的实施.

Anything more specific depends on your implementation.

希望这会有所帮助!

这篇关于如何在 AngularJS 中存储当前用户上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆