ProductPromotion
Logo

Angular.JS

made by https://0x3d.site

GitHub - cyrilletuzi/angular-async-local-storage: Efficient client-side storage for Angular: simple API + performance + Observables + validation
Efficient client-side storage for Angular: simple API + performance + Observables + validation - cyrilletuzi/angular-async-local-storage
Visit Site

GitHub - cyrilletuzi/angular-async-local-storage: Efficient client-side storage for Angular: simple API + performance + Observables + validation

GitHub - cyrilletuzi/angular-async-local-storage: Efficient client-side storage for Angular: simple API + performance + Observables + validation

Async local storage for Angular

Efficient client-side storage for Angular:

  • simplicity: simple API similar to native localStorage,
  • perfomance: internally stored via the asynchronous indexedDB API,
  • Angular-like: wrapped in RxJS Observables,
  • security: validate data with a JSON Schema or with typebox,
  • compatibility: works around some browsers issues and heavily tested via GitHub Actions,
  • documentation: API fully explained, and a changelog!

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

  • storing null or undefined 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.

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:

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

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

More Resources
to explore the angular.

mail [email protected] to add your project or resources here 🔥.

Related Articles
to learn about angular.

FAQ's
to learn more about Angular JS.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory