简体   繁体   中英

how to store login info with angularJS

I am currently develloping a little app with angularJS; the users have to go through a login form and then they can click on a few links who display data fetched from a server.

The login form only takes the user's input and it is then "stored" into a factory

app.factory('IdFormHolder', function () {
    var that = this;

    that.setId = function (data) {
        that = data;

    };
    that.getId = function () {
        return that;
    };

    return that;
});

Which works fine I need to keep it stored because the server requires the login form to be sent each time I do a $http.get as a header.

Each controller takes the login form from the factory and uses it to get the data from the server.

This works fine until someone decides to refresh the page, at which point it seems the factory is "emptied" from its login form, and the web-app then fails to show anything.

Is there a way to store this login info so that it doesn't get erased so easily ?

You can use this code after youve installed sessionStorage:

app.factory('IdFormHolder', ['$sessionStorage', function ($sessionStorage) {
    var that = this;

    that.setId = function (data) {
        $sessionStorage.id = data;
        that = data;

    };
    that.getId = function () {
        return $sessionStorage.id;
    };

    return that;
}]);

Download Link: https://github.com/gsklee/ngStorage

In order to persist data you'd have to use some kind of local DB || LocalStorage || SessionStorage at least. When initializing the Factory you could check and attempt to retrieve from DB/LS that data and hold it as a variable if it does exist.

Something like

app.factory('IdFormHolder', function () {
    this.heldId = attemptToGetSavedDataFromSomewhere(); // would be null otherwise

    this.setId = (id) => {
        this.heldId = id;
    };

    this.getId = () => this.heldId;

    return this;
});

Using angular-local-storage you can access to the browsers local storage:

app.factory('IdFormHolder', function(localStorageService) {
    return {
        setId: function(data) {
            return localStorageService.set('loggedUserData', data);
        },
        getId: function() {
            return localStorageService.get('loggedUserData');
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM