Can I or Should I use a Global variable in Angularjs to store a logged in user?

前端 未结 4 995
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 08:41

I\'m new to angular and developing my first \'real\' application. I\'m trying to build a calendar/scheduling app ( source code can all be seen on github ) and I want to be a

相关标签:
4条回答
  • 2020-12-22 09:05

    Just to add on my comment and your edit. Here is what the code would look like if you wanted to be able to re-use your user service and insert it into other apps.

    angular.module('user', []).service('userService', [function(){
       //declare your user properties and methods
    }]) 
    
    angular.module('myApp', ['user'])
    .controller('myCtrl', ['userService', '$scope', function(userService, scope){
        // you can access userService from here
    }])
    

    Not sure if that's what you wanted but likewise you could have your "user" module have a dependency to another "parent" module and access that module's data the same way.

    0 讨论(0)
  • 2020-12-22 09:15

    Yes you can do it in $rootScope. However, I believe it's better practice to put it inside a service. Services are singletons meaning they maintain the same state throughout the application and as such are prefect for storing things like a user object. Using a "user" service instead of $rootScope is just better organization in my opinion. Although technically you can achieve the same results, generally speaking you don't want to over-populate your $rootScope with functionality.

    0 讨论(0)
  • 2020-12-22 09:18

    If your (single) page is rendered dynamically by the server and the server knows if you are logged-in or not, then you could do the following:

    Dynamically render a script tag that produces:

    <script>
         window.user = { id: 1234, name: 'User A', isLoggedIn: true };
    </script>
    

    For non logged-in users:

    <script>
         window.user = { isLoggedIn: false };
    </script>
    

    For convinience, copy user to a value inside angular's IOC:

    angular.module('myApp').value('user', window.user);
    

    Then, you can use it in DI:

    angular.module('myApp').factory('myService', function(user) {
        return {
            doSomething: function() {
                if (user.isLoggedIn) {
                    ...
                } else {
                    ...
                }
            }
        };
    });
    

    Something tricky (which you should thing twice before doing [SEE COMMENTS]) is extending the $scope:

    angular.module('myApp').config(function($provide) {
        $provide.decorator('$controller', function($delegate, user) {
            return function(constructor, locals) {
                locals.$scope._user = user;
                return $delegate(constructor, locals);
            };
        });
    });
    

    This piece of code decorates the $controller service (responsible for contructing controllers) and basically says that $scope objects prior to being passed to controllers, will be enhanced with the _user property.

    Having it automatically $scoped means that you can directly use it any view, anywhere:

    <div ng-if="_user.isLoggedIn">Content only for logged-in users</div>
    

    This is something risky since you may end up running into naming conflicts with the original $scope API or properties that you add in your controllers.

    It goes without saying that these stuff run solely in the client and they can be easily tampered. Your server-side code should always check the user and return the correct data subset or accept the right actions.

    0 讨论(0)
  • 2020-12-22 09:21

    You can have a global user object inside the $rootScope and have it injected in all your controllers by simply putting it into the arguments of the controller, just as you do with $scope. Then you can implement functionalities in a simple check: if($rootScope.user). This allows you to model the user object in any way you want and where you want, acting as a global variable, inside of Angular's domain and good practices with DI.

    0 讨论(0)
提交回复
热议问题