ohboy21
ohboy21

Reputation: 4319

How to handle user model in an AngularJS application?

I am refactoring an AngularJS application, and there, almost everything is stored in the $rootScope.

In my old applications I've build with Angular, I created a Service for each model, and then instantiated it within a Controller when needed.

I ask myself: Is it ok to store the whole user object inside the $rootScope or what is best practice here?

How can I get sure to create a user during login and then pass it around throughout the whole application?

Upvotes: 0

Views: 519

Answers (3)

İlker Korkut
İlker Korkut

Reputation: 3250

It seems ok generally storing user like models in $rootScope. But In my opinion it's not a best practise in angularjs(However I have used $rootScope way before).

Factory is the one of angularjs' beauty. Generally we use it to call rest services. But also you can create a model with it. Also you will be able to extend your model easily with injecting another model. That's just an idea , may be there is another better options to use model like objects in angularjs.

Lets look an example

 // User Model   
 app.factory('User', function() {
    var User = function(username) {
        this.username = username;
        this.email = null;
    };

    User.prototype.getDetails = function() {
        var self = this;
        return self.username;
    };

    return User;
});

// ExtendedUser Model
app.factory('ExtendedUser', function(User) {
    var ExtendedUser = function() {
       User.apply(this, arguments);
    };

    ExtendedUser.prototype = new User();

    function getEmail() {
       var self = this;
       // You can make an http call to get email like information as an extra
       self.email = "[email protected]";
       return self;
    }

    ExtendedUser.prototype.getDetails = function() {
       var self = this;
       var extendedUser = getEmail();
       return extendedUser;
    };
    return ExtendedUser;
});

Upvotes: 1

Enkode
Enkode

Reputation: 4793

I would look into a0-angular-storage: https://github.com/auth0/angular-storage It is great for storing user information / tokens or whatever to be retrieved throughout your app.

Key Features

Uses localStorage or sessionStorage by default but if it's not available, it uses ngCookies. Lets you save JS Objects, If you save a Number, you get a Number, not a String Uses a caching system so that if you already have a value, it won't get it from the store again.

Upvotes: 1

kamil-mrzyglod
kamil-mrzyglod

Reputation: 5008

If you don't want to store user model in $rootScope you can use private JS variable, which can be accessed by some service in Angular(since both factory and a service are singleton in Angular).

The nice addition is that it is harder to determine where the user model is stored, the only thing you need is proper encapsulation and code structure.

Upvotes: 0

Related Questions