How do I store a current user context in AngularJS?

后端 未结 2 2012
渐次进展
渐次进展 2020-11-29 15:00

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 applicati

2条回答
  •  余生分开走
    2020-11-29 15:27

    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.

    Hope this helps!

提交回复
热议问题