Giter VIP home page Giter VIP logo

born2net / angular2-async-local-storage Goto Github PK

View Code? Open in Web Editor NEW

This project forked from cyrilletuzi/angular-async-local-storage

0.0 3.0 1.0 66 KB

Efficient local storage module for Angular 2 : 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.

License: MIT License

TypeScript 96.02% JavaScript 3.98%

angular2-async-local-storage's Introduction

Async local storage for Angular 2

Efficient local storage module for Angular 2 : 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 2 asynchronous modules.

Why this module ?

For now, Angular 2 does not provide a local storage module, and almost every app needs some local storage. There is 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 asychronous and efficient, but it's a mess to use : you'll soon be caught by the callbacks hell, as it does not support Promises yet.

Mozilla has done a very great job with the localForage library : a simple API based on native localStorage API, but internally stored via the asynchronous IndexedDB API for performance. But it is written in ES5 and then it's a mess to include into Angular.

This module is based on the same idea as localForage, but in ES6/ES2015 and additionnaly wrapped into RxJS Observables to be homogeneous with other Angular modules.

Getting started

Install via npm :

npm install angular2-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 'angular2-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 'angular2-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',
      ...
      'angular2-async-local-storage': 'node_modules/angular2-async-local-storage/bundles/async-local-storage.umd.js'
    }
    ...
});

API

The API follows the native localStorage API, except it's asynchronous via RxJS Observables.

Writing data

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(() => {}, () => {});

Reading data

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'
}, () => {});

Browser support

All browsers supporting IndexedDB, ie. all current browsers : Firefox, Chrome, Opera, Safari, Edge and IE10+.

IE8/9 are supported but use native localStorage as a fallback, so internal operations are synchronous (the public API remains asynchronous).

Older or special browsers (like Opera Mini) not supporting IndexedDB and localStorage use a fake storage, so the data won't be persistent but the module won't crash.

This module is not impacted by IE/Edge missing IndexedDB features.

This module has not been tested against Safari 8/9 buggy IndexedDB implementation, but it uses very basic features of IndexedDB so it may be fine. Otherwise, use the IndexedDBshim polyfill.

AoT and Universal support

This module supports AoT pre-compiling and Universal server-side rendering.

Changelog

Changelog available here.

Roadmap

  • Unit tests.
  • Cache / preload ?

License

MIT

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.