In addition to the classic localStorage
-like API, this library also provides a partial Map
-like API for advanced operations.
To use it:
import { StorageMap } from '@ngx-pwa/local-storage';
export class AngularComponentOrService {
constructor(private storage: StorageMap) {}
}
An Observable
iterating over keys in storage:
this.storage.keys().subscribe({
next: (key) => {
console.log(key);
},
complete: () => {
console.log('Done');
},
});
Note
This is an iterating Observable
:
- if there is no key, the
next
callback will not be invoked, - if you need to wait the whole operation to end, be sure to act in the
complete
callback, as thisObservable
can emit several values and so will invoke thenext
callback several times.
Gives you an Observable
telling you if a key exists in storage:
this.storage.has('someindex').subscribe((result) => {
if (result) {
console.log('The key exists :)');
} else {
console.log('The key does not exist :(');
}
});
Number of items stored in storage.
this.storage.size.subscribe((size) => {
console.log(size);
});
.values()
and .entries()
have not been implemented on purpose, because it has few use cases and it would not be a good idea for performance. But you can easily do your own implementation via keys()
.
As a convenience, below are some recipes for advanced operations asked by the community.
Let us say you stored:
- some app's data with such indexes:
app_data1
,app_data2
... - some user's data with such indexes:
user_data1
,user_data2
...
You can then delete only app data:
import { filter, mergeMap } from 'rxjs';
this.storage.keys().pipe(
/* Keep only keys starting with 'app_' */
filter((key) => key.startsWith('app_')),
/* Remove the item for each key */
mergeMap((key) => this.storage.delete(key))
).subscribe({
complete: () => {
/* Note we do not act in the classic success callback as it will be trigerred for each key,
* while we want to act only when all the operations are done */
console.log('Done!');
}
});