简体   繁体   English

如何使用angularJS存储登录信息

[英]how to store login info with angularJS

I am currently develloping a little app with angularJS; 我目前正在使用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. 效果很好,我需要将其保存起来,因为每次我将$ http.get作为标题时,服务器都需要发送登录表单。

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. 在有人决定刷新页面之前,此方法工作正常,此时似乎工厂已从其登录表单“清空”,然后Web应用程序无法显示任何内容。

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: 安装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 下载链接: https : //github.com/gsklee/ngStorage

In order to persist data you'd have to use some kind of local DB || 为了保留数据,您必须使用某种本地数据库||。 LocalStorage || LocalStorage || SessionStorage at least. SessionStorage至少。 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. 初始化Factory时,您可以检查并尝试从DB / LS检索该数据并将其保存为变量(如果存在)。

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: 使用angular-local-storage,您可以访问浏览器的本地存储:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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