Efficient client-side storage for Angular:
localStorage
,indexedDB
API,Observable
s,typebox
,[!TIP] I am also the author of the Angular Schematics extension for Visual Studio Code, installed 1 million times. Feel free to give it a try.
Angular does not provide a client-side storage service, and almost every app needs some client-side storage. There are 2 native JavaScript APIs available:
The localStorage
API is simple to use but synchronous, so if you use it too often, your app will soon begin to freeze.
The indexedDB
API is asynchronous and efficient, but it is a mess to use: you will soon be caught by the callback hell, as it does not support Promise
s.
This library has a simple API similar to native localStorage
, but internally stores data via the asynchronous indexedDB
for performance. All of this powered by RxJS.
Install the package:
# For Angular LTS (Angular >= 16):
ng add @ngx-pwa/local-storage
Done!
If for any reason ng add
does not work, follow the manual installation guide.
[!NOTE] Angular versions <= 15 are officially outdated.
To update to new versions, see the migration guides.
import { StorageMap } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(private storage: StorageMap) {}
}
This service API is similar to the standard Map
API, and close to the standard localStorage
API.
class StorageMap {
// Write
set(index: string, value: unknown): Observable<undefined> {}
delete(index: string): Observable<undefined> {}
clear(): Observable<undefined> {}
// Read (one-time)
get(index: string): Observable<unknown> {}
get<T>(index: string, schema: JSONSchema): Observable<T> {}
// Advanced
watch(index: string): Observable<unknown> {}
watch<T>(index: string, schema: JSONSchema): Observable<T> {}
size: Observable<number>;
has(index: string): Observable<boolean> {}
keys(): Observable<string> {}
}
const user: User = { firstName: 'Henri', lastName: 'Bergson' };
this.storage.set('user', user).subscribe(() => {});
[!NOTE] You can store any value, without worrying about serializing. But note that:
- storing
null
orundefined
makes no sense and can cause issues in some browsers, so the item will be removed instead,- you should stick to serializable JSON data, meaning primitive types, arrays and literal objects.
Date
,Map
,Set
,Blob
and other special structures can cause issues in some scenarios. Read the serialization guide for more details.
To delete one item:
this.storage.delete('user').subscribe(() => {});
To delete all items:
this.storage.clear().subscribe(() => {});
To get the current value:
this.storage.get('user').subscribe((user) => {
console.log(user);
});
Not finding an item is not an error, it succeeds but returns undefined
:
this.storage.get('notexisting').subscribe((data) => {
data; // undefined
});
[!IMPORTANT] You will only get one value: the
Observable
is here for asynchrony but is not meant to emit again when the stored data is changed. If you need to watch the value, read the watching guide.
Do not forget it is client-side storage: always check the data, as it could have been forged.
You should use a JSON Schema to validate the data.
this.storage.get('test', { type: 'string' }).subscribe({
next: (user) => { /* Called if data is valid or `undefined` */ },
error: (error) => { /* Called if data is invalid */ },
});
[!TIP] Read the full validation guide to learn how to validate all common scenarios.
You do NOT need to unsubscribe: the Observable
autocompletes (like in the Angular HttpClient
service).
But you DO need to subscribe, even if you do not have something specific to do after writing in storage (because it is how RxJS Observable
s work).
this.storage.set('user', user); // Does nothing
As usual, it is better to catch any potential error:
this.storage.set('color', 'red').subscribe({
next: () => {},
error: (error) => {},
});
For read operations, you can also manage errors by providing a default value:
import { catchError, of } from 'rxjs';
this.storage.get('color').pipe(
catchError(() => of('red')),
).subscribe((result) => {});
[!TIP] Read the errors guide for some details about what errors can happen.
This lib, as native localStorage
and indexedDb
, is about persistent storage.
Wanting temporary storage (like sessionStorage
) is a very common misconception: an application does not need that.
[!TIP] Read the expiration guide.
Map
-like operationsIn addition to the classic localStorage
-like API, this library also provides a Map
-like API for advanced operations:
.keys()
.has(key)
.size
[!TIP] Read the Map-like operations guide for more info and some recipes. For example, it allows to implement a multiple databases scenario.
This library supports the same browsers as Angular.
[!TIP] Read the browsers support guide for more details and special cases.
The library has configurable options if you have multiple apps on the same subdomain and you do not want to share data between them.
[!TIP] Read the collision guide.
The library has configurable options for interoperability when mixing this library with direct usage of native APIs or other libraries like localForage
(which does not make sense in most cases).
[!TIP] Read the interoperability documentation.
Changelog available here, and migration guides here.
MIT