Home

Awesome

Async local storage for Angular

Efficient client-side storage for Angular:

[!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.

Why this library?

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 Promises.

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.

Getting started

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.

Upgrading

To update to new versions, see the migration guides.

API

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> {}
}

How to

Writing data

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:

Deleting data

To delete one item:

this.storage.delete('user').subscribe(() => {});

To delete all items:

this.storage.clear().subscribe(() => {});

Reading data

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.

Checking data

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.

Subscription

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 Observables work).

this.storage.set('user', user); // Does nothing

Errors

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.

Expiration

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 operations

In addition to the classic localStorage-like API, this library also provides a Map-like API for advanced operations:

[!TIP] Read the Map-like operations guide for more info and some recipes. For example, it allows to implement a multiple databases scenario.

Support

Browser support

This library supports the same browsers as Angular.

[!TIP] Read the browsers support guide for more details and special cases.

Collision

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.

Interoperability

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

Changelog available here, and migration guides here.

License

MIT