{

Angular LocalStorage, SessionStorage example | Ngx-webstorage tutorial


We are going to learn how to store user data in web storage in the Angular application.

In the Angular 13 tutorial, You are about to learn how to save user data to local storage and session in browsers.

Localstorage in Angular

In this tutorial, we are going to learn the following things

  • Localstorage in Angular
  • SessionStorage in Angular
  • Ngx-webstorage angular

You can check my previous post on Html5 web storage APIs with examples.
LocalStroage is a browser storage mechanism to store a data

Data is stored with key and value pairs

Angular 13 Local Storage Example

  • Step 1 Create Angular Application
  • Step 2 Install Dependencies
  • Step 3 Create Component
  • Step 4 Create Session Storage Service
  • Step 5 update App Component
  • Step 6 Start Angular app

Create Angular Application

If you don’t have an angular application, don’t worry; running the command below will generate one for you.

you can use the ng new command to build an Angular application

ng new angular-service-examples

Go to root folder

cd angular-service-examples

Angular 13 ngx-webstorage example

When your application needs access to web storage APIs, you could use HTML5’s APIs directly.

However, to accommodate all use cases, you’ll need to write a lot of code. Instead, makes use of well-known libraries such as ngx-webstorage.

ngx-webstorage is an npm library and wrapper API for managing LocalStorage and SessionStorage objects from Nodejs Applications.

The advantages of using external libraries such as ngx-webstroage are When a browser doesn’t implement the Web storage API, it utilizes the standard browser storage cookie and session cookie.

Angular applications are typescript-based. We need a library which is based on typescript.

It provides easy services which you can integrate into your Angular application. There are a lot of other modules are there which do the same thing, but this module has support for future versions. This has support for the NPM package manager.

install ngx-webstorage using npm

First download ngx-webstorage library using npm command below

npm, install --save ngx-webstorage. 

It installs as project dependency and saves under the project node_module folder. --save option update this module to package.json with below entry under dependencies sections.

"ngx-webstorage": "^9.0.0",  

configure in Angular Application, Once installed, First need to register the module in your Root module, For that, import Ng2Webstorage in your main module.

Ng2Webstorage has different services LocalStorageService - service wrapper for LocalStorage SessionStorageService - service wrapper for SessionStorage

import {NgModule} from '@angular/core';  
import {BrowserModule} from '@angular/platform-browser';  
import {NgxWebstorageModule} from 'ngx-webstorage';  
   
@NgModule({  
    imports: [  
        BrowserModule,  
        NgxWebstorageModule.forRoot(),  
  
    ],  
})  
export class AppModule {  
}  

Next step, Inject LocalStorageService,SessionStorageService into your component

import {Component} from '@angular/core';  
import {LocalStorageService} from 'ngx-webstorage';  
   
@Component({  
    selector: 'storageTest',  
    template: `  
        

  

  
`,  
})  
export class StorageComponent {  
   
    attribute;  
   
    constructor(private storage:LocalStorageService) {}  
   
// save the  data using store methods  
this.storage.store('key', 'test');  
   
//retrieve using the key in string   
 this.storage.retrieve('key');  
}  

instead of directly injecting into the component, Always write a code that does all the operations related to this service in a common utility service API, so that all components can be reused like this. SessionStorageService also does the provides same methods as LocalStorageService

@LocalStorage @SessionStorage Decorators

Decorators is used to decorate classes and methods like annotations in java language. Please see the below example of how the code is updating session storage with decorators

 @SessionStorage('key')  
    mykey;  
   
    modifyValue() {  
        this.mykey.push('testvalue for a key');  
        this.mykey = this.mykey;   
    }

The same code works in Angular 2,4,5 and 6 versions.

ngx web storage methods

The below methods available for both local storage as well as session storage
Store( key: string, value: any ): void
-save the key and value if the key doesn’t exist. if the key exists, update value.
Retrieve( key:string ):any

  • this retrieve the value for a specific key
    Clear( key?: string ): void
  • this removes storage for specific key
    IsStorageAvailable(): boolean
    -This returns true, if local storage/ session storage support available returns false, if not supported
    Observe( key?: string ): EventEmitter
    -This returns Event Emitter and used to observe the key of the storage object

Please ping me if you have any questions/need more clarifications

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Best 5 ways to remove the duplicate object from array In javascript| Fastest way delete duplicates in typescript

Best Five ways to iterate enum in typescript with examples?

Best Ways to convert timestamp to Date format in typescript| Angular timestamp date example

How to Convert JSON Object to Interface or class in typescript?

How to Convert Number to/from String in typescript?

How to create an array of multiple types in Typescript

How to declare static constants in Typescript and Angular