Angular async local storage
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.
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.
Getting startard with ngx-pwa/local-storage
With Angular ≥6, install via npm:
Now you can inject the service where you need it:
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:
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.
By the same author
- Angular schematics extension for VS Code : GUI for Angular CLI commands
- @ngx-pwa/local-storage: 1st Angular library for local storage
- Library @ngx-pwa/offline
- Other popular Angular posts on Medium
- Follow me on Twitter
- Angular onsite trainings (based in Paris, so the website is in French, but my English bio is here and I’m open to travel)