How to keep globally current user until logout with angular_devise?

前端 未结 5 785
挽巷
挽巷 2021-02-18 18:29

How to create own service accessible globally that will call server by currentUser() only once on page load, if User is logged in then keep it and provide data to c

5条回答
  •  不思量自难忘°
    2021-02-18 19:17

    As we know factory is a singleton object and basically it is used for data sharing. We can inject it to any controller and functions as an dependency .So this may be also solve your problem. inject this service to your state resolve block and check if user exists or not if not then call the fetch user function of factory

    app.factory("User", function($http, $q, $rootScope) {
    var user = null;
    return {
        fetchUser: function() {
            /*your ajax call that return current user*/
            user = YOUR_SERVER_RESPONSE;
            return user;
    
        },
        getUser : function(){
            return user;
        },
        setUser : function(u){
            user = u;
        }
    }
    

    });

    and your state config block is look like

      .state('dashboard', {
      url: '/dashboard',
      templateUrl: 'dashboard.html',
      resolve : function(User){
        if(User.getUser()){
            return User.getUser();
        }else{
            return User.fetchUser();
        }
      }
    })
    

提交回复
热议问题