Async local storage for Angular
Efficient client-side storage module for Angular apps and Progressive Wep Apps (PWA):
- simplicity: based on native
localStorage
API, - perfomance: internally stored via the asynchronous
indexedDB
API, - Angular-like: wrapped in RxJS
Observable
s, - security: validate data with a JSON Schema,
- compatibility: works around some browsers issues,
- documentation: API fully explained, and a changelog!
- reference: 1st Angular library for client-side storage according to ngx.tools.
By the same author
Why this module?
For now, Angular does not provide a client-side storage module, 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's a mess to use:
you'll soon be caught by the callback hell, as it does not support Promise
s yet.
Mozilla has done a very great job with the localForage
library:
a simple API based on native localStorage
,
but internally stored via the asynchronous indexedDB
for performance.
But it's built in ES5 old school way and then it's a mess to include into Angular.
This module is based on the same idea as localForage
, but built in ES6+
and additionally wrapped into RxJS Observable
s
to be homogeneous with other Angular modules.
Getting started
Install the right version according to your Angular one via npm
:
npm install @ngx-pwa/local-storage@next
npm install @ngx-pwa/local-storage@6
Since version 8, this second step is:
- not required for the lib to work,
- strongly recommended for all new applications, as it allows interoperability
and is future-proof, as it should become the default in a future version,
- prohibited in applications already using this lib and already deployed in production,
as it would break with previously stored data.
import { StorageModule } from '@ngx-pwa/local-storage';
@NgModule({
imports: [
StorageModule.forRoot({
IDBNoWrap: true,
})
]
})
export class AppModule {}
Must be done at initialization, ie. in AppModule
, and must not be loaded again in another module.
Upgrading
If you still use the old angular-async-local-storage
package, or to update to new versions,
see the migration guides.
Versions 4 & 5, which are not supported anymore,
needed an additional setup step explained in the old module guide.
API
2 services are available for client-side storage, you just have to inject one of them were you need it.
LocalStorage
import { LocalStorage } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(private localStorage: LocalStorage) {}
}
This service API follows the
native localStorage
API,
except it's asynchronous via RxJS Observable
s:
class LocalStorage {
length: Observable<number>;
getItem(index: string, schema?: JSONSchema): Observable<unknown> {}
setItem(index: string, value: any): Observable<true> {}
removeItem(index: string): Observable<true> {}
clear(): Observable<true> {}
}
StorageMap
import { StorageMap } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(private storageMap: StorageMap) {}
}
New since version 8 of this lib, this service API follows the
native Map
API
and the new upcoming standard kv-storage API,
except it's asynchronous via RxJS Observable
s.
It does the same thing as the LocalStorage
service, but also allows more advanced operations.
If you are familiar to Map
, we recommend to use only this service.
class StorageMap {
size: Observable<number>;
get(index: string, schema?: JSONSchema): Observable<unknown> {}
set(index: string, value: any): Observable<undefined> {}
delete(index: string): Observable<undefined> {}
clear(): Observable<undefined> {}
has(index: string): Observable<boolean> {}
keys(): Observable<string> {}
}
How to
The following examples will show the 2 services for basic operations,
then stick to the StorageMap
API. But except for methods which are specific to StorageMap
,
you can always do the same with the LocalStorage
API.
Writing data
let user: User = { firstName: 'Henri', lastName: 'Bergson' };
this.storageMap.set('user', user).subscribe(() => {});
this.localStorage.setItem('user', user).subscribe(() => {});
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 JSON data, ie. primitive types, arrays and literal objects.
Map
, Set
, Blob
and other special structures can cause issues in some scenarios.
See the serialization guide for more details.
Deleting data
To delete one item:
this.storageMap.delete('user').subscribe(() => {});
this.localStorage.removeItem('user').subscribe(() => {});
To delete all items:
this.storageMap.clear().subscribe(() => {});
this.localStorage.clear().subscribe(() => {});
Reading data
this.storageMap.get<User>('user').subscribe((user) => {
console.log(user);
});
this.localStorage.getItem<User>('user').subscribe((user) => {
console.log(user);
});
Not finding an item is not an error, it succeeds but returns:
undefined
with StorageMap
this.storageMap.get('notexisting').subscribe((data) => {
data;
});
this.localStorage.getItem('notexisting').subscribe((data) => {
data;
});
Note you'll only get one value: the Observable
is here for asynchrony but is not meant to
emit again when the stored data is changed. And it's normal: if app data change, it's the role of your app
to keep track of it, not of this lib. See #16
for more context and #4
for an example.
Checking data
Don't forget it's client-side storage: always check the data, as it could have been forged.
You can use a JSON Schema to validate the data.
this.storageMap.get('test', { type: 'string' }).subscribe({
next: (user) => { },
error: (error) => { },
});
See the full validation guide to see 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 don't have something specific to do after writing in storage
(because it's how RxJS Observable
s work).
Errors
As usual, it's better to catch any potential error:
this.storageMap.set('color', 'red').subscribe({
next: () => {},
error: (error) => {},
});
For read operations, you can also manage errors by providing a default value:
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
this.storageMap.get('color').pipe(
catchError(() => of('red')),
).subscribe((result) => {});
Could happen to anyone:
.setItem()
: storage is full (DOMException
with name 'QuotaExceededError
)
Could only happen when in localStorage
fallback:
.setItem()
: error in JSON serialization because of circular references (TypeError
).setItem()
: trying to store data that can't be serialized like Blob
, Map
or Set
(SerializationError
from this lib).getItem()
: error in JSON unserialization (SyntaxError
)
Should only happen if data was corrupted or modified from outside of the lib:
.getItem()
: data invalid against your JSON schema (ValidationError
from this lib)- any method when in
indexedDB
: database store has been deleted (DOMException
with name NotFoundError
)
Could only happen when in Safari private mode:
.setItem()
: trying to store a Blob
Other errors are supposed to be catched or avoided by the lib,
so if you were to run into an unlisted error, please file an issue.
Map
-like operations
Starting with version >= 8 of this lib, in addition to the classic localStorage
-like API,
this lib also provides a Map
-like API for advanced operations:
See the documentation for more info and some recipes.
For example, it allows to implement a multiple databases scenario.
Support
Angular support
We follow Angular LTS support,
meaning we support Angular >= 6, until November 2019.
This module supports AoT pre-compiling.
This module supports Universal server-side rendering
via a mock storage.
Browser support
All browsers supporting IndexedDB, ie. all current browsers :
Firefox, Chrome, Opera, Safari, Edge, and IE10+.
See the browsers support guide for more details and special cases (like private browsing).
Collision
If you have multiple apps on the same subdomain and you don't want to share data between them,
see the prefix guide.
Interoperability
For interoperability when mixing this lib with direct usage of native APIs or other libs like localForage
(which doesn't make sense in most cases),
see the interoperability documentation.
Changelog
Changelog available here, and migration guides here.
License
MIT