Angular async local storage

There is a feature nearly all JavaScript frameworks avoid: local storage. For now, it’s missing in Angular too. So I created a module.

A French version of this post is available here.

Why a local storage module?

Angular is a full framework to build web apps, with all the modules needed: components, AJAX, routing… There is only one thing missing: local storage.

Nearly every app need at least some local storage, especially a Progressive Web App (PWA), to save an auth token or user settings and profile. So for now there is only two options: use an additional tool like Ionic, or use the native JavaScript APIs. There are 2 of them:

The localStorage API is simple to use but synchronous. So if you use it too often, your app will soon start to freeze.

IndexedDB API is asynchronous, so efficient, but it’s a mess to use: you’ll soon fall in the callback hell, as it works with a ton of old events listeners (no Promises yet).

Mozilla did a great job with localForage: an easy-to-use API, similar to native localStorage, but internally saving data asynchronously via IndexedDB. But it’s written in ES5, so it’s difficult to implement it in Angular.

Here comes our ngx-pwa/local-storage module: same idea as localForage, but in ES6/ES2015, and wrapped in RxJS observables, to be coherent with other Angular modules.

Getting startard with ngx-pwa/local-storage

With Angular ≥6, install via npm:

npm install @ngx-pwa/local-storage

Now you can inject the service where you need it:

LocalStorage API

The API follows the native localStorage API, except it’s asynchronous via RxJS Observables.

Writing data

Errors are unlikely to happen, but in an app you should always catch all potential errors.

You do not need to unsubscribe : the observable autocompletes (like in the Http service).

You can store any value, without worrying about stringifying.

To delete one item:

To delete all items:

Reading data

Not finding an item is not an error, it succeeds but returns null.

So always check the data as it may have been removed from local storage.

Support and changelog

This module works in all modern browsers, and is compatible with AoT pre-compiling and Universal server rendering.

Note that this post is just an introduction, you’ll find more details on Github. Also, I don’t check comments here, so if you have a question or an issue, please do it on Github.

By the same author