search

Home  >  Q&A  >  body text

angular.js - $cookies or $rootScope, which one is more suitable for storing user data information?

if (user.username && user.password) {
    loginService.loginUser(user).then(
        function(response) {
            $cookies.put("token", response.token)
            $rootScope.token = response.token
            $cookies.put("username", response.username)
            }
}

The token can also be stored directly in $rootScope, so what is the use of $cookies?

过去多啦不再A梦过去多啦不再A梦2780 days ago757

reply all(2)I'll reply

  • 阿神

    阿神2017-05-15 17:16:24

    My personal understanding is that $rootScope is actually only stored in memory. If the page is refreshed, the contents of $rootScope will be cleared.
    Cookies do not have such problems, but the storage capacity of cookies is somewhat limited

    reply
    0
  • PHPz

    PHPz2017-05-15 17:16:24

    This involves the difference between persistent storage and temporary ($rootScope) storage. In addition, localStorage and sessionStorage are also defined in the HTML5 specification. In addition, if you use the above storage solution, it will involve object serialization and deserialization. The method of using $rootScope does not involve the above content. Finally, if you are interested, please check out the advantages and disadvantages of different storage methods. If you are building a webapp, you can further understand the problems existing in localStorage under low memory. To summarize, choose a storage method based on whether the data needs to be persisted.

    reply
    0
  • Cancelreply