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.
npm install angular-cyanez-local-storage
npm install angular-async-local-storage --save
`
Then include the AsyncLocalStorage module in your app root module. It works like the HttpModule,
providing a global service to the whole app, so do NOT re-import it in your own sub modules.
`
import { AsyncLocalStorageModule } from 'angular-async-local-storage';
@NgModule({
imports: [
BrowserModule,
AsyncLocalStorageModule,
...
]
...
})
export class AppModule {}
`
Now you just have to inject the service where you need it :
`
import { AsyncLocalStorage } from 'angular-async-local-storage';
@Injectable()
export class YourService {
public constructor(protected storage: AsyncLocalStorage) {}
public ngOnInit() {
this.storage.setItem('lang', 'fr').subscribe(() => {
// Done
});
}
}
`
If you use System.js loading in developpement,
configure the module path like for other Angular modules :
`
System.config({
...
map: {
'@angular/core': 'node_modules/@angular/core/bundles/core.umd.js',
...
'angular-async-local-storage': 'node_modules/angular-async-local-storage/bundles/async-local-storage.umd.js'
}
...
});
`
API
The API follows the native localStorage API,
except it's asynchronous via RxJS Observables.
$3
Errors are unlikely to happen, but in an app you should always catch all potential errors.
You do NOT need to unsubscribe : the observable autocompletes (like in the Http service).
`
this.storage.setItem('color', 'red').subscribe(() => {
// Done
}, () => {
// Error
});
`
You can store any value, without worrying about stringifying.
`
this.storage.setItem('user', { firstName: 'Henri', lastName: 'Bergson' })
.subscribe(() => {}, () => {});
`
To delete one item :
`
this.storage.removeItem('user').subscribe(() => {}, () => {});
`
To delete all items :
`
this.storage.clear().subscribe(() => {}, () => {});
`
$3
Not finding an item is not an error, it succeeds but returns null.
`
this.storage.getItem('notexisting').subscribe((data) => {
data; // null
}, () => {
// Not called
});
`
So always check the data as it may have been removed from local storage.
`
this.storage.getItem('user').subscribe((user) => {
if (user != null) {
user.firstName; // 'Henri'
}
}, () => {});
`
As any data can be stored, you need to type your data manually :
`
this.storage.getItem('color').subscribe((color: string) => {
color; // 'red'
}, () => {});
``