How to keep globally current user until logout with angular_devise?

前端 未结 5 778
挽巷
挽巷 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

    I solved the issue of current_user information with angular by adding the following JavaScript (jQuery) code to the bottom of my main HTML page:

    $("meta[name=current_user]").data('current_user', {
        id: <%=j current_user.id.to_s %>, 
        username: "<%=j current_user.full_name.to_s %>"
    });
    

    You can parse in whatever information you need, this happens to be a Rails Project and all I needed was the ID and NAME (with the ID I could query the User factory object and receive a JSON with full information if I needed).

    Then in your AngularJS Controller you can add (mine is coffeescript):

    # Grab User Info
    current_user = angular.element("meta[name=current_user]").data 'current_user'
    
    # Stop Here if you Have the Info you Need
    $scope.user = current_user
    
    # **** OR Get More Info if User is Logged In 
    if current_user.id is not undefined
       $scope.user = User.get {id: current_user.id}
    

    Here is my Factory Code for the User (coffeescript again):

    # In order to prevent minification from effecting the code
    # must wrap functions as arrays and pass in the variables as 
    # strings before the function call
    app.factory "User", ["$resource", ($resource) ->
        $resource("/api/angular/users/:id", 
        { id: "@id" }, 
        {
            update: { method: "PUT" }
        })
    ]
    

    Let me know if you have any questions.

提交回复
热议问题