How to save your app state in localStorage with Angular

I have been experimenting with Angular 5 for the last 2 months and this week I started creating simple apps to test what I have learned. I fetched and stored data to Firebase using the HttpClient Module.

What if want to storage my app state locally? Well, I know that in Vanilla JavaScript we can use the localSorage or sessionStorage.

 

For example

// Store
localStorage.setItem("email", "email@example.com");

// Fetch
document.getElementById("result").innerHTML = localStorage.getItem("email");

 

But…do I have to use vanilla JavaScript on a project where I am coding in TypeScript? Do I have to create a custom Angular service from scratch? No worries, a angular-webstorage-service solves that problem. Keep reading find out what you need to do.

Installation

Install and add the npm dependency to package.json in your project by running the following command.

npm install --save angular-webstorage-service

Import Module

In your AppModule file add the following imports.

import { NgModule } from ‘@angular/core’;
import { StorageServiceModule } from ‘angular-webstorage-service’;

@NgModule({
 imports: [ StorageServiceModule ]
})

Configure your Service

Since you want to handle the app state, you need to create Service to call the StorageServiceModule functionalities.

Necessary Imports

import { Inject, Injectable } from ‘@angular/core’;
import { SESSION_STORAGE, StorageService } from ‘angular-webstorage-service’;

 

In my example I am storing a to-do list in an array of objects to Local Storage. Every time I try to store any new task to local storage, I make a copy of it, push the new task and put the updated array into local storage.

 

import { Inject, Injectable } from '@angular/core';
import { SESSION_STORAGE, StorageService } from 'angular-webstorage-
service';


// key that is used to access the data in local storage
const STORAGE_KEY = 'local_todolist';

@Injectable()
export class LocalStorageService {
    anotherTodolist = [];

    constructor(@Inject(SESSION_STORAGE) private storage:        StorageService) { }

    public storeOnLocalStorage(taskTitle: string): void {

        //get array of tasks from local storage
        const currentTodoList = this.storage.get(STORAGE_KEY) || [];

        // push new task to array
        currentTodoList.push({
           title: taskTitle,
           isChecked: false
        });

        // insert updated array to local storage
        this.storage.set(STORAGE_KEY, currentTodoList);

        console.log(this.storage.get(STORAGE_KEY) || 'LocaL storage is empty');
    }
}

 

Remember to inject the StorageService in your constructor with special attention to

@Inject(SESSION_STORAGE)

 

I do not have a function to get the the data from the Local Storage but I do call get() to fetch the array right after I save it.

this.storage.get(STORAGE_KEY)

 

To remove data from simply call.

this.storage.remove(STORAGE_KEY)

 

For more information about this module head to their npm page. You might want to save you app state in session storage instead. They have different bundles to ECMAScript 6 and ECMAScript 5.


Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *

*