[javascript] Local storage in Angular 2

I need to store data in the browser's session and retrieve the data until the session exits. How do you use local and session storage in Angular 2?

This question is related to javascript angular local-storage session-variables

The answer is


Save into LocalStorage:

localStorage.setItem('key', value);

For objects with properties:

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

Get From Local Storage:

localStorage.getItem('key');

For objects:

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

localStorage Object will save data as string and retrieve as string. You need to Parse desired output if value is object stored as string. e.g. 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.


To set the item or object in local storage:

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

To get the item or object in local storage, you must remember your key.

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

To remove it from local storage:

   localStorage.removeItem('yourKey');

The standard localStorage API should be available, just do e.g.:

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

It's pretty widely supported.

Note that you will need to add "dom" to the "lib" array in your tsconfig.json if you don't already have it.


Use Angular2 @LocalStorage module, which is described as:

This little Angular2/typescript decorator makes it super easy to save and restore automatically a variable state in your directive (class property) using HTML5' LocalStorage.

If you need to use cookies, you should take a look at: https://www.npmjs.com/package/angular2-cookie


You can use cyrilletuzi's LocalStorage Asynchronous Angular 2+ Service.

Install:

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

Usage:

// 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');

More info here:

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


The syntax of set item is

localStorage.setItem(key,value);

The syntax of get item is

localStorage.getItem(key); 

An example of this is:

localStorage.setItem('email','[email protected]');
    let mail = localStorage.getItem("email");
    if(mail){ 
       console.log('your email id is', mail);
    }
  }

Local Storage Set Item

Syntax:

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

Example:

  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...
    }
  }

also you can use

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

Session Storage Set Item

Syntax:

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

Example:

  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...
    }
  }

also you can use

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

Store and Retrieve data easily


Really elegant solution are decorators. You can use them to mark variables you want to store.

export class SomeComponent {

  @LocalStorage
  public variableToBeStored: string;

}

Example how to achieve it is in this article (my blog)


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');
  }
}

install

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

first of all you need to Install "angular-2-local-storage"

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

Save into LocalStorage:

localStorage.setItem('key', value);

Get From Local Storage:

localStorage.getItem('key');

As said above, should be: localStorageService.set('key', 'value'); and localStorageService.get('key');


How to store, retrieve & delete data from localStorage:

// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings. So we stringify the value(if it's an object) before setting it.

// So, if you have an object as a value 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 a note at the end of this answer for tips about 
// using an angular package for a cleaner & smoother storage usage.

A quick tip:
You can also use a package for your angular app, that is based on native localStorage API (that we are using above) to achieve this and you don't have to worry about stringify and parse. Check out this package for angular 5 and above. @ngx-pwa/local-storage

You can also do a quick google search for maybe ,angular local storage, & find a package that has even more Github stars etc.

Check out this page to know more about Web Storage API.


You can also consider using library maintained by me: ngx-store (npm i ngx-store)

It makes working with localStorage, sessionStorage and cookies incredibly easy. There are a few supported methods to manipulate the data:

1) Decorator:

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 
  }
}

Variables stored by decorators can be also shared across different classes - there is also @TempStorage() (with an alias of @SharedStorage())) decorator designed for it.

2) Simple service methods:

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) Builder pattern:

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);
    }
}

Another important thing is you can listen for (every) storage changes, e.g. (the code below uses RxJS v5 syntax):

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() returns a regular Observable, so you can zip, filter, bounce them etc.

I'm always open to hearing suggestions and questions helping me to improve this library and its documentation.


Install "angular-2-local-storage"

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

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);

To get an item from LocalStorage :

window.localStorage.getItem(key);

You can only store a string in LocalStorage; if you have an object, first you have to convert it to string like the following:

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

And when you want to get an object from LocalStorage :

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

All Tips above are the same for SessionStorage.

You can use the following service to work on SessionStorage and LocalStorage. All methods in the service :

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

Inject this service in your components, services and ...; Do not forget to register the service in your core module.

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);
      }
    }
  }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to local-storage

Angular 6: saving data to local storage Is it safe to store a JWT in localStorage with ReactJS? How to save to local storage using Flutter? Setting and getting localStorage with jQuery Local storage in Angular 2 How to store token in Local or Session Storage in Angular 2? QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota What is the difference between localStorage, sessionStorage, session and cookies? How to save an image to localStorage and display it on the next page? Can local storage ever be considered secure?

Examples related to session-variables

Local storage in Angular 2 Set session variable in laravel Session variables not working php Setting session variable using javascript How to use sessions in an ASP.NET MVC 4 application? Check if PHP session has already started How to use store and use session variables across pages? MySQL wait_timeout Variable - GLOBAL vs SESSION How do servlets work? Instantiation, sessions, shared variables and multithreading How to empty/destroy a session in rails?