How to keep globally current user until logout with angular_devise?

前端 未结 5 780
挽巷
挽巷 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:27

    I've had to deal with user Authentication in a large Angular app and found this article very useful: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

    Specific to 'how to make it happen only once':

    • you can call the init() of the Service in an app.run block
    • adding it as a resolve requirement of an outer state for the app (if you use nested states)

    A UserService Service to represent user's logged in state works well for sharing state throughout the application. The login and logout functions can be exposed through this service and the user's details can be stored here too. Defining a UserApi that extends $resource will probably help too to separate the actual HTTP concerns from managing user state.

    Other concerns that will catch you, both of which are covered in the article: persistent state across page refreshes, and having areas of the site that are only accessible when the user is logged in.

提交回复
热议问题