Angular 2中的本地存储

Jay*_*B A 139 javascript session-variables local-storage angular

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

jon*_*rpe 139

标准localStorageAPI应该可用,例如:

localStorage.setItem('whatever', 'something');
Run Code Online (Sandbox Code Playgroud)

得到了广泛的支持.

请注意,如果您还没有数组,则需要添加"dom""lib"数组中tsconfig.json.

  • @Winnemucca *"throwing fits"* 不是一个有用的问题陈述。我不记得在 Angular CLI 包含的内容之外添加任何内容。 (2认同)
  • localStorage.getItem('key'); localStorage.setItem('key','value'); (2认同)

Jun*_*aid 86

要将数据存储在本地存储中,

localStorage.setItem('key', 'value');
Run Code Online (Sandbox Code Playgroud)

确保字符串化值,例如,如果您有一个对象
localStorage.setItem(itemName, JSON.stringify(itemData));

或单个键值对
localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));

并从localstorage中检索数据
user = JSON.parse(localStorage.getItem('currentUser'));

编辑:您还可以使用基于本机localStoreage api(我们在上面使用)的包来实现这一点,您不必担心stringify和parse.检查此包装的角度为5及以上.@ NGX-PWA /本地存储

  • 感谢JSON解析提示! (3认同)

Nab*_*ada 35

保存到LocalStorage:

localStorage.setItem('key', value);
Run Code Online (Sandbox Code Playgroud)

对于具有属性的对象:

localStorage.setItem('key', JSON.stringify(object));
Run Code Online (Sandbox Code Playgroud)

从本地存储获取:

localStorage.getItem('key');
Run Code Online (Sandbox Code Playgroud)

对象:

JSON.parse(localStorage.getItem('key'));
Run Code Online (Sandbox Code Playgroud)

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

最好使用框架提供的localStroage而不是第三方库localStorageService或其他任何东西,因为它会减少您的项目大小.


ebu*_*sho 16

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

这个小的Angular2/typescript装饰器使用HTML5'LocalStorage可以非常轻松地在指令(类属性)中自动保存和恢复变量状态.

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

  • 这目前没有人维护它. (4认同)
  • angular2-cookie项目的继任者是ngx-cookie https://www.npmjs.com/package/ngx-cookie (2认同)

Hin*_*ich 15

下面是一个简单服务的示例,它使用localStorage来持久保存数据:

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

要使用此服务,请在您的应用程序中的某些模块中提供它,例如在核心模块中.然后像这样使用:

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 太棒了!,只是做了一个相同的示例脚本.url:https://stackblitz.com/edit/localstorage-angular-example?file=src%2Fapp%2Fapp.component.ts (3认同)

Kar*_*mar 9

本地存储集项

句法:

  localStorage.setItem(key,value);
  localStorage.getItem(key);
Run Code Online (Sandbox Code Playgroud)

例:

  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...
    }
  }
Run Code Online (Sandbox Code Playgroud)

你也可以用

    localStorage.setItem("name", JSON.stringify("Muthu"));
Run Code Online (Sandbox Code Playgroud)

会话存储集项

句法:

  sessionStorage.setItem(key,value);
  sessionStorage.getItem(key);
Run Code Online (Sandbox Code Playgroud)

例:

  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...
    }
  }
Run Code Online (Sandbox Code Playgroud)

你也可以用

   sessionStorage.setItem("name", JSON.stringify("Muthu"));
Run Code Online (Sandbox Code Playgroud)

轻松存储和检索数据


Dan*_*cal 8

您也可以考虑使用由我维护的库: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 
  }
}
Run Code Online (Sandbox Code Playgroud)

装饰器存储的变量也可以在不同的类之间共享-还为它设计了@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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个重要的事情是您可以侦听(每个)存储更改,例如(以下代码使用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')
  });
Run Code Online (Sandbox Code Playgroud)

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

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


小智 7

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

  • 还没有在api网站上找到关于localStorageService的文档,在哪里可以找到它? (2认同)

Rah*_*gal 6

我们可以轻松地使用localStorage设置数据和接收数据。

注意:它同时适用于angular2和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;
Run Code Online (Sandbox Code Playgroud)


Abo*_*zlR 6

存储在LocalStorage

window.localStorage.setItem(key, data);
Run Code Online (Sandbox Code Playgroud)

从 中删除项目LocalStorage

window.localStorage.removeItem(key);
Run Code Online (Sandbox Code Playgroud)

从 获取项目LocalStorage

window.localStorage.getItem(key);
Run Code Online (Sandbox Code Playgroud)

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

window.localStorage.setItem(key, JSON.stringify(obj));
Run Code Online (Sandbox Code Playgroud)

当您想从LocalStorage以下位置获取对象时:

const result=JSON.parse(window.localStorage.getItem(key));
Run Code Online (Sandbox Code Playgroud)

上面的所有提示对于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
Run Code Online (Sandbox Code Playgroud)

在你的组件、服务和……中注入这个服务;不要忘记在核心模块中注册该服务。

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);
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)