ngxs-labs / async-storage-plugin

⏱ WIP: Async Storage Plugin
MIT License
34 stars 12 forks source link

How to create async storage with NGXS #156

Open SteveLemire opened 4 years ago

SteveLemire commented 4 years ago

I was able to manage our own storage service that provides functionality to support async storage with the help of StorageMap library that use IndexedDb and AsyncStorageEngine.

  1. Install StorageMap .

  2. Install AsyncStorageEngine

  3. Create a new storage service and implement AsyncStorageEngine with missing members like this:

    export class StorageService implements AsyncStorageEngine {
    constructor(private storageMap: StorageMap}
  4. In your app.module.ts, configure your NgxsModule and other packages like this:

    NgxsModule.forRoot(
      [
        // Add your state classes here
      ],
      {
        developmentMode: !environment.production,
        selectorOptions: {
          // https://www.ngxs.io/concepts/select#selector-options
          // These Selector Settings are recommended in preparation for NGXS v4
          suppressErrors: false,
          injectContainerState: false,
        },
      },
    ),
    // https://github.com/ngxs-labs/async-storage-plugin
    NgxsAsyncStoragePluginModule.forRoot(StorageService),
    // https://github.com/ngxs-labs/async-storage-plugin
    NgxsDataPluginModule.forRoot([NGXS_DATA_STORAGE_PLUGIN]),
  5. In your state class, add the following decorators:

    @Persistence({
    useClass: StorageService,
    })
    @StateRepository()
    @State<MyStateModel>({...

Et voilà! You can now use your async StorageService with NGXS!

Note: This will not work with IE11 and target type ES5 because ngxs-lab/data @Persistence decorator use the Package class that is only available with ES6 (ES2015). I was not able get this work event if I tried with the following packages:

Originally posted by @SteveLemire in https://github.com/ngxs-labs/data/issues/299#issuecomment-631042493