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

查看:83
本文介绍了如何在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天全站免登陆