How to store config values in ionic?

this.storage.get('userData').then((val: UserData) => {
   //at this point val will have its intellisense
});

It is often better to have the access to storage going via a provider instead of interacting with it directly, as you may later on wish to switch the implementation to something else without having to update your code in 40 places :slight_smile:

It’s also a bit cleaner in terms of your method calls.

Here’s my implementation of something I call key-value-provider.ts…

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class KeyValueProvider {

  constructor(private storage: Storage) {

  }

  async get<T>(key: string) {

    let payload = (await this.storage.get(key));

    return payload as T;
  }

  async remove(key: string) {
    await this.storage.remove(key);
    return true;
  }

  async set(key: string, val: any) {

    let payload = val;

    await this.storage.set(key, payload);
    return true;
  }

  async hasKey(key: string) {

    const allKeys = await this.storage.keys();

    const truthy = allKeys.some(k => k === key);

    return truthy;
  }

}

When you grab your object you would do something like…

   async getMyValue(){
      const value = this.keyValueProvider.get<UserData>('userData);
      return value;
   }
2 Likes