Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
@ngx-pwa/local-storage
Advanced tools
Efficient local storage module for Angular apps and PWA: simple API based on native localStorage API, but internally stored via the asynchronous IndexedDB API for performance, and wrapped in RxJS observables to be homogeneous with other Angular modules.
Efficient client-side storage module for Angular apps and Progressive Wep Apps (PWA):
localStorage
API,indexedDB
API,Observable
s,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.
Install the package, according to your Angular version:
# For Angular 8 & 9:
ng add @ngx-pwa/local-storage
# For Angular 6 & 7:
npm install @ngx-pwa/local-storage@6
Done!
You should stick to these commands. If for any reason ng add
does not work,
be sure to follow the manual installation guide,
as there are additionnal steps to do in addition to the package installation for some versions.
For version >= 8, if you have multiple applications in the same project, as usual, you need to choose the project:
ng add @ngx-pwa/local-storage --project yourprojectname
If you still use the old angular-async-local-storage
package, or to update to new versions,
see the migration guides.
2 services are available for client-side storage, you just have to inject one of them where you need it.
StorageMap
: recommendedNew since version 8 of this lib, this is the recommended service:
import { StorageMap } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(private storage: StorageMap) {}
}
This service API follows the
new standard kv-storage
API,
which is similar to the standard Map
API,
except it's based on RxJS Observable
s instead of Promise
s:
class StorageMap {
// Read
get(index: string): Observable<unknown> {}
get<T>(index: string, schema: JSONSchema): Observable<T> {}
// Write
set(index: string, value: any): Observable<undefined> {}
delete(index: string): Observable<undefined> {}
clear(): Observable<undefined> {}
// Advanced
size: Observable<number>;
has(index: string): Observable<boolean> {}
keys(): Observable<string> {}
}
It does the same thing as the localStorage
API, but also allows more advanced operations.
LocalStorage
: legacyYou can keep this legacy service in existing apps, but it's not recommended anymore for new applications.
import { LocalStorage } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(private localStorage: LocalStorage) {}
}
This service API follows the
standard localStorage
API,
except it's asynchronous via RxJS Observable
s:
class LocalStorage {
// Read
getItem(index: string): Observable<unknown> {}
getItem<T>(index: string, schema: JSONSchema): Observable<T> {}
// Write
setItem(index: string, value: any): Observable<true> {}
removeItem(index: string): Observable<true> {}
clear(): Observable<true> {}
// Advanced
length: Observable<number>;
}
The following examples will use the recommended StorageMap
service.
But for older versions, you can always do the same with the LocalStorage
service.
let user: User = { firstName: 'Henri', lastName: 'Bergson' };
this.storage.set('user', user).subscribe(() => {});
You can store any value, without worrying about serializing. But note that:
null
or undefined
makes no sense and can cause issues in some browsers, so the item will be removed instead,Date
, Map
, Set
, Blob
and other special structures can cause issues in some scenarios.
See the serialization guide for more details.To delete one item:
this.storage.delete('user').subscribe(() => {});
To delete all items:
this.storage.clear().subscribe(() => {});
this.storage.get('user').subscribe((user) => {
console.log(user);
});
Not finding an item is not an error, it succeeds but returns undefined
(or null
with LocalStorage
legacy service):
this.storage.get('notexisting').subscribe((data) => {
data; // undefined
});
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. If you need to watch the value,
version 9 introduced a watch()
method, see the watching guide.
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.storage.get('test', { type: 'string' }).subscribe({
next: (user) => { /* Called if data is valid or `undefined` */ },
error: (error) => { /* Called if data is invalid */ },
});
See the full validation guide to see 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 don't have something specific to do after writing in storage
(because it's how RxJS Observable
s work).
As usual, it's 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 { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
this.storage.get('color').pipe(
catchError(() => of('red')),
).subscribe((result) => {});
See 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 doesn't need that. More details here.
Map
-like operationsStarting 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:
.keys()
.has(key)
.size
See the documentation for more info and some recipes. For example, it allows to implement a multiple databases scenario.
We follow Angular LTS support, meaning we support Angular >= 7, until April 2020.
This module supports AoT pre-compiling and Ivy.
This module supports Universal server-side rendering via a mock storage.
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).
If you have multiple apps on the same subdomain and you don't want to share data between them, see the prefix guide.
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 available here, and migration guides here.
MIT
FAQs
Efficient local storage module for Angular: simple API based on native localStorage API, but internally stored via the asynchronous IndexedDB API for performance, and wrapped in RxJS observables to be homogeneous with other Angular modules.
The npm package @ngx-pwa/local-storage receives a total of 12,417 weekly downloads. As such, @ngx-pwa/local-storage popularity was classified as popular.
We found that @ngx-pwa/local-storage demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.