Kurai Bankusu Kurai Bankusu - 1 year ago 82
AngularJS Question

Storing User Data in the $rootScope - Good or Bad?

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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download