How to save your app state in localStorage with Angular

Tiago Valverde
3 min readMar 13, 2018

--

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 ngx-webstorage-service

Import Module

In your AppModule file add the following imports.

import { NgModule } from ‘@angular/core’;
import { StorageServiceModule } from ‘ ngx-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 { LOCAL_STORAGE, StorageService } from ‘ngx-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 { LOCAL_STORAGE, StorageService } from 'ngx-webstorage-service';
// key that is used to access the data in local storageconst STORAGE_KEY = 'local_todolist';@Injectable()
export class LocalStorageService {
anotherTodolist = [];
constructor(@Inject(LOCAL_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(LOCAL_STORAGE)

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

To remove data from simply call this.storage.remove(STORAGE_KEY).

Once your service is setup you have to add the server created in the providers array in app.module.ts

@NgModule({
providers: [LocalStorageService],
})

Finally, import your local storage service in a component, declare a instance of it in the constructor and call the service method that performs the operations to the local storage. In the snippet below, just for the tutorial, I call the service directly from the hook ngOnInit so a new task is inserted to local storage every time the component is rendered.

import { LocalStorageService } from './services/localStorage.service';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { constructor(private localStorageService: LocalStorageService) {} ngOnInit(): void { const newTodo = 'new todo';
this.localStorageService.storeOnLocalStorage(newTodo);
}
}

If you run your app and make use of the component that calls the service and then go to the DevTools, select the Application tab, click Local Storage and your url the todo list will be displayed.

Note: Post updated recently not only because I used SESSION_STORAGE and not LOCAL_STORAGE, which was misleading but also because the npm package was renamed. Thanks to the readers Mike Goodstadt and nik pol.

I am Software Engineer in the making at Ryerson University and FreeCodeCamp. If you want to know more about me you can head to my website, Github, Twitter or Instagram.

--

--

Tiago Valverde

Softwarer Developer, Computer Science Student at Ryerson University, fitness, soccer and motorcycle enthusiast.