我如何保存在角当前用户上下文? [英] How do I store a current user context in Angular?

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

问题描述

我有一个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; }
    ...
  };
});

您可以在任意一个你的控制器引用此。下面code手表从服务价值的变化(通过调用指定的函数),然后同步改变的数值范围。

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.

希望这有助于!

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

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