1

I'm building an Angularjs application that needs to access a logged-in user's information within several different modules (user profile, liking posts, commenting). I'm aware that if certain data needs to be shared between disparate parts of an Angularjs app, it's desirable to use a service or factory. But what about the $rootScope, like so?

.run(function($rootScope, userService) {
  userService.getLoggedInUser()
    .then(function(user){
      $rootScope.loggedInUser = user; // Contains username, joined date, photo URL, etc.
    })
})

If I need the user's info within any part of the app, I can simply fetch it from the root

<div >Username: {{ $root.loggedInUser.username }} </div>
...
alert($rootScope.username());

Does this expose the application in any negative way? I'm not introducing any sensitive information like passwords or email, but maybe I'm overlooking something obvious.

Any input is appreciated!

Clay Banks
  • 4,483
  • 15
  • 71
  • 143

2 Answers2

3

As a general rule, you don't want to store your data on $rootScope in the same way you don't want to store variables in Javascript on global scope.

The advantage of storing the data in a service is that you can encapsulate the data, make it available through a unique API of the service and the service can manipulate it - it knows how to retrieve it from a server, or how to store changes back to server.

In any case it could also depend on the size and purpouse of your application. If it's a small school project or a personal web site, it won't probably hurt you in the long run anyway and you can save time now having it on a $rootScope.

davekr
  • 2,266
  • 1
  • 26
  • 32
1

You can use sessionStorage instead. You can read/write to it and access it on the fly

pedrum golriz
  • 513
  • 8
  • 27