Angular 2中的本地存储

2020/10/31 18:04 · javascript ·  · 0评论

我需要将数据存储在浏览器的会话中并检索数据,直到会话退出。您如何在Angular 2中使用本地和会话存储?

标准localStorageAPI应该可用,例如:

localStorage.setItem('whatever', 'something');

得到了广泛的支持

请注意,如果您还没有阵列,则需要将其添加"dom""lib"阵列中tsconfig.json

如何从localStorage存储,检索和删除数据:

// General syntax for storing data
localStorage.setItem('key', 'value');

// And if you have an object that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));

// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));

// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));

// To remove a value/item from localStorage
localStorage.removeItem("some-key");


// see the note at the end of this answer for a tip about 
// using an angular package for a cleaner & smoother storage usage.

查看此页面以了解有关Web Storage API的更多信息。

也可以为您的angular应用程序使用一个基于本机localStorage API(我们在上面使用过)的软件包来实现此目的,而不必担心字符串化和解析。检出此包装的角度为5及以上。@ ngx-pwa / local-storage

您也可以对Google进行快速Google搜索,查找有角度的本地存储,并找到包含更多Github星等的包。

保存到LocalStorage中:

localStorage.setItem('key', value);

对于具有属性的对象:

localStorage.setItem('key', JSON.stringify(object));

从本地存储获取:

localStorage.getItem('key');

对于对象:

JSON.parse(localStorage.getItem('key'));

localStorage对象会将数据另存为字符串,并以字符串检索如果值是对象存储为字符串,则需要解析所需的输出。例如parseInt(localStorage.getItem('key'));

It is better to use framework provided localStroage instead of 3rd party library localStorageService or anything else because it reduces your project size.

Here is an example of a simple service, that uses localStorage to persist data:

import { Injectable } from '@angular/core';

@Injectable()
export class PersistanceService {
  constructor() {}

  set(key: string, data: any): void {
    try {
      localStorage.setItem(key, JSON.stringify(data));
    } catch (e) {
      console.error('Error saving to localStorage', e);
    }
  }

  get(key: string) {
    try {
      return JSON.parse(localStorage.getItem(key));
    } catch (e) {
      console.error('Error getting data from localStorage', e);
      return null;
    }
  }
}

To use this services, provide it in some module in your app like normal, for example in core module. Then use like this:

import { Injectable } from '@angular/core';

@Injectable()
export class SomeOtherService {

  constructor(private persister: PersistanceService) {}

  someMethod() {
    const myData = {foo: 'bar'};
    persister.set('SOME_KEY', myData);
  }

  someOtherMethod() {
    const myData = persister.get('SOME_KEY');
  }
}

使用Angular2 @LocalStorage模块,其描述为:

这个小的Angular2 / typescript装饰器使使用HTML5'LocalStorage在指令(类属性)中自动保存和恢复变量状态变得非常容易。

如果需要使用cookie,则应查看:https :
//www.npmjs.com/package/angular2-cookie

本地存储集项目

句法:

  localStorage.setItem(key,value);
  localStorage.getItem(key);

例:

  localStorage.setItem("name","Muthu");
  if(localStorage){   //it checks browser support local storage or not
    let Name=localStorage.getItem("name");
    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

你也可以用

    localStorage.setItem("name", JSON.stringify("Muthu"));

会话存储集项目

句法:

  sessionStorage.setItem(key,value);
  sessionStorage.getItem(key);

例:

  sessionStorage.setItem("name","Muthu");

  if(sessionStorage){ //it checks browser support session storage/not
    let Name=sessionStorage.getItem("name");

    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

你也可以用

   sessionStorage.setItem("name", JSON.stringify("Muthu"));

轻松存储和检索数据

您也可以考虑使用由我维护的库:ngx-storenpm i ngx-store

它使使用localStorage,sessionStorage和cookie变得异常简单。有一些支持的方法来处理数据:

1)装饰器:

export class SomeComponent {
  @LocalStorage() items: Array<string> = [];

  addItem(item: string) {
    this.items.push(item);
    console.log('current items:', this.items);
    // and that's all: parsing and saving is made by the lib in the background 
  }
}

装饰器存储的变量也可以在不同的类之间共享-还为它设计了@TempStorage()(带有别名@SharedStorage())装饰器。

2)简单的服务方式:

export class SomeComponent {
  constructor(localStorageService: LocalStorageService) {}

  public saveSettings(settings: SettingsInterface) {
    this.localStorageService.set('settings', settings);
  }

  public clearStorage() {
    this.localStorageService.utility
      .forEach((value, key) => console.log('clearing ', key));
    this.localStorageService.clear();
  }
}

3)构建器模式:

interface ModuleSettings {
    viewType?: string;
    notificationsCount: number;
    displayName: string;
}

class ModuleService {
    constructor(public localStorageService: LocalStorageService) {}

    public get settings(): NgxResource<ModuleSettings> {
        return this.localStorageService
            .load(`userSettings`)
            .setPath(`modules`)
            .setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array 
            .appendPath(this.moduleId)
            .setDefaultValue({});
    }

    public saveModuleSettings(settings: ModuleSettings) {
        this.settings.save(settings);
    }

    public updateModuleSettings(settings: Partial<ModuleSettings>) {
        this.settings.update(settings);
    }
}

另一个重要的事情是,您可以侦听(每个)存储更改,例如(以下代码使用RxJS v5语法):

this.localStorageService.observe()
  .filter(event => !event.isInternal)
  .subscribe((event) => {
    // events here are equal like would be in:
    // window.addEventListener('storage', (event) => {});
    // excluding sessionStorage events
    // and event.type will be set to 'localStorage' (instead of 'storage')
  });

WebStorageService.observe() 返回常规的Observable,因此您可以对其进行压缩,过滤,反射等操作。

我总是乐于听取建议和问题,以帮助我改进此库及其文档。

如上所述,应为:localStorageService.set('key', 'value');localStorageService.get('key');

We can easily use the localStorage for setting the data and receiving the data.

Note: it works with both angular2 and angular 4

//set the data
localStorage.setItem(key, value);   //syntax example
localStorage.setItem('tokenKey', response.json().token);

//get the data
localStorage.getItem('tokenKey')

//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;

To store in LocalStorage :

window.localStorage.setItem(key, data);

To remove an item from LocalStorage :

window.localStorage.removeItem(key);

从以下位置获取物品LocalStorage

window.localStorage.getItem(key);

您只能将字符串存储在中LocalStorage如果有对象,则首先必须将其转换为如下所示的字符串:

window.localStorage.setItem(key, JSON.stringify(obj));

当您想从中获取对象时LocalStorage

const result=JSON.parse(window.localStorage.getItem(key));

上面的所有提示均与相同SessionStorage

您可以使用以下服务来处理SessionStorageLocalStorage服务中的所有方法:

getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void 
removeAllLocals(): void

在您的组件,服务和...中注入此服务;不要忘记在核心模块中注册服务。

import { Injectable } from '@angular/core';

@Injectable()
export class BrowserStorageService {

  getSession(key: string): any {
    const data = window.sessionStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setSession(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.sessionStorage.setItem(key, data);
  }

  removeSession(key: string): void {
    window.sessionStorage.removeItem(key);
  }

  removeAllSessions(): void {
    for (const key in window.sessionStorage) {
      if (window.sessionStorage.hasOwnProperty(key)) {
        this.removeSession(key);
      }
    }
  }

  getLocal(key: string): any {
    const data = window.localStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setLocal(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.localStorage.setItem(key, data);
  }

  removeLocal(key: string): void {
    window.localStorage.removeItem(key);
  }

  removeAllLocals(): void {
    for (const key in window.localStorage) {
      if (window.localStorage.hasOwnProperty(key)) {
        this.removeLocal(key);
      }
    }
  }
}

设置项目的语法是

localStorage.setItem(key,value);

get item的语法是

localStorage.getItem(key); 

例如:

localStorage.setItem('email','abc@gmail.com');
    let mail = localStorage.getItem("email");
    if(mail){ 
       console.log('your email id is', mail);
    }
  }

真正优雅的解决方案是装饰器。您可以使用它们来标记要存储的变量。

export class SomeComponent {

  @LocalStorage
  public variableToBeStored: string;

}

如何实现它的示例在本文中(我的博客)

安装“ angular-2-local-storage”

import { LocalStorageService } from 'angular-2-local-storage';

您可以使用cyrilletuzi的LocalStorage异步Angular 2+服务

安装:

$ npm install --save @ngx-pwa/local-storage

用法:

// your.service.ts
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {
   constructor(private localStorage: LocalStorage) { }
}

// Syntax
this.localStorage
    .setItem('user', { firstName:'Henri', lastName:'Bergson' })
    .subscribe( () => {} );

this.localStorage
    .getItem<User>('user')
    .subscribe( (user) => { alert(user.firstName); /*should be 'Henri'*/ } );

this.localStorage
    .removeItem('user')
    .subscribe( () => {} );

// Simplified syntax
this.localStorage.setItemSubscribe('user', { firstName:'Henri', lastName:'Bergson' });
this.localStorage.removeItemSubscribe('user');

更多信息在这里:

https://www.npmjs.com/package/@ngx-pwa/local-storage
https://github.com/cyrilletuzi/angular-async-local-storage

要在本地存储中设置项目或对象:

   localStorage.setItem('yourKey', 'yourValue');

要将项目或对象存储在本地存储中,必须记住密钥。

   let yourVariable = localStorage.getItem('yourKey');

要将其从本地存储中删除:

   localStorage.removeItem('yourKey');

安装

npm install --save @ngx-pwa/local-storage

首先,您需要安装“ angular-2-local-storage”

import { LocalStorageService } from 'angular-2-local-storage';

保存到LocalStorage中:

localStorage.setItem('key', value);

从本地存储获取:

localStorage.getItem('key');
本文地址:http://javascript.askforanswer.com/angular-2zhongdebendicunchu.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!