Gabriel Lopes
Gabriel Lopes

Reputation: 943

AngularJS, Factory, Provider or Services

I'm trying to save a variable in my application containing the username, I have a login page (a directive) where I get the username. I tried:

Provider: it save my variable but I can only change before the app load and I need to change the variable after inside a controller.

.provider('username',function(){

    var username = 'Default';

    return {
        setName: function(value) { 
            username = value; 
        },
        $get: function() { 
            return { 
                 name: username 
            } 
        }
    }

Services: it works ok, but if I refresh the page I lose the variable.

.service('username', function () {

    var username;
    this.setName = function (value) {
        username = value;
    }
    this.name = function () {
        return username;
    }
})

Can some tell me what is the best approach for that? I'm struggling for hours to come up with something..

Upvotes: 1

Views: 393

Answers (2)

sebastienbarbier
sebastienbarbier

Reputation: 6832

I usually use a factory, seems perfect, but like you said you lose all your data when refreshing your page.

This behavious is not related to Angular of Factory object, but to Javascript and your browser. You need to save this value in a storage object (cookies, sessionStorage, localStorage, here is a link if you never used them : Difference between Session Storage, Local Storage and Cookies in AngularJS).

In you case, in this.setName you store it in let's say sessionStorage, and when initializing your factory you just check if this value exist.

.service('username', function ($window) {
    var username = $window.sessionStorage.getItem('user');
    this.setName = function (value) {
        username = value;
        $window.sessionStorage.setItem('user', value);
    }
    this.name = function () {
        return username;
    }
})

(This code might not be perfect, like if the value does not exist might be good to have a dedicated scenario, but give you a good idea about how to use it in your case)

Upvotes: 0

svarog
svarog

Reputation: 9839

You should make a factory service that uses your browser's local storage/session storage to store session data

try going over these questions

Maintaining Session through Angular.js

AngularJS: Service vs provider vs factory

Upvotes: 1

Related Questions