npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ngforage/ngforage-ng4

v1.0.5

Published

localForage bindings for Angular 4

Downloads

317

Readme

ngforage

localForage bindings for Angular 4 and 5

Release Demo and documentation Build Status Coverage Status Greenkeeper badge

Tested on Safari Tested on Chrome Tested on Firefox

Table of Contents

Installation

The metadata version for Angular's AOT compiler differs between Angular 4.x and Angular 5.x, therefore two flavours of this library are released:

| Flavour | Angular 4 | Angular 5 | |-----------|--------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------| | Local | npm install @ngforage/ngforage-ng4 | npm install @ngforage/ngforage-ng5 | | CDN | Package | Package |

The UMD global name is ngForage.

Types and polyfills

Ensure that the following are available globally:

  • Promise
  • Object.assign

Importing the module

Replace ngforage with @ngforage/ngforage-ng4 or @ngforage/ngforage-ng5 depending on which version of Angular you're using.

import {NgModule} from "@angular/core";
import {NgForageModule} from "ngforage";

@NgModule({
  imports: [
    NgForageModule
  ]
})
export class MyModule {

}

Usage

Using the Standard Store

import {ChangeDetectionStrategy, Component} from "@angular/core";
import {NgForage, NgForageConfig} from "ngforage";

@Component({
  selector: 'my-component',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: 'foo'
})
export class MyComponent {

  constructor(private readonly ngf: NgForage) {

  }

  async getSomething() {
    const clickCount = await this.ngf.getItem<number>('clickCount');

    console.log(`${clickCount === null ? 'No' : clickCount} clicks.`);
  }

  async setSomething() {
    await this.ngf.setItem('foo', {bar: 'qux'});
  }

  async removeSomething() {
    await this.ngf.removeItem('foo');
  }

  async removeEverything() {
    await this.ngf.clear();
  }

  async getNumberOfItems() {
    console.log(`There are ${await this.ngf.length()} items stored!`);
  }

  async printKeysStored() {
    const keys: string[] = await this.ngf.keys();

    console.log('Keys:', keys.sort().join("\n"));
  }

  async checkIfDriverIsSupported() {
    const supports = this.ngf.supports(NgForageConfig.DRIVER_INDEXEDDB);

    console.log(`IndexedDB is ${supports ? '' : 'not '}supported`);
  }
}

Using the Cache Store

The cache store can be used as a replacement for NgForage, but also supports the following operations:

import {ChangeDetectionStrategy, Component} from "@angular/core";
import {CachedItem, NgForageCache} from "ngforage";

@Component({
  selector: 'my-component',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: 'foo'
})
export class MyComponent {

  constructor(private readonly ngfc: NgForageCache) {

  }

  async setSomething() {
    // Use default expiry time
    await this.ngfc.setCached('foo', 'bar');

    // Cache for one minute
    await this.ngfc.setCached('qux', {baz: 1}, 60000);
  }

  async getSomething() {
    const item: CachedItem<string> = await this.ngfc.getCached<string>('foo');

    if (item.hasData) {
      console.log(`The item is ${item.data}`);
    } else {
      console.log('No data found');
    }

    if (item.expired) {
      console.log('Item has expired');
    } else {
      const expiryDate: Date = item.expires;

      console.log(`The item will expire in ${Math.round(item.expiresIn / 1000)} seconds, on ${expiryDate.toLocaleString()}`);
    }
  }

  async removeSomething() {
    await this.ngfc.removeCached('foo');
  }
}

Configuration

Global Configuration

import {NgModule} from "@angular/core";
import {NgForageConfig, NgForageModule, NgForageOptions} from "ngforage";

@NgModule({
  imports: [
    NgForageModule
  ]
})
export class MyModule {

  constructor(conf: NgForageConfig) {
    // Set the database name
    conf.name = 'myDB';

    // Set the store name (e.g. in IndexedDB this is the dataStore)
    conf.storeName = 'my_store';

    // Set default cache time to 5 minutes
    conf.cacheTime = 300000;

    // Set driver to local storage
    conf.driver = NgForageConfig.DRIVER_LOCALSTORAGE;

    // Set the driver to indexed db if available,
    // falling back to websql
    // falling back to local storage
    conf.driver = [
      NgForageConfig.DRIVER_INDEXEDDB,
      NgForageConfig.DRIVER_WEBSQL,
      NgForageConfig.DRIVER_LOCALSTORAGE
    ];

    // Set websql database size
    conf.size = 1024 * 1024 * 4;

    // Set DB version. Currently unused.
    conf.version = 2.0;

    // Configure in bulk
    const bulk: NgForageOptions = {
      version: 3.0,
      name: 'newDB'
    };
    conf.configure(bulk);
  }
}

Instance-Level Configuration

You can configure ngForage on an instance level. If need be, every component can have its own instance:

import {ChangeDetectionStrategy, Component} from "@angular/core";
import {NgForage, NgForageCache} from "ngforage";

@Component({
  selector: 'my-component',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: 'foo',
  providers: [
    NgForage,
    NgForageCache
  ]
})
export class MyComponent {

  constructor(private readonly store: NgForage,
              private readonly cache: NgForageCache) {

  }
}

NgForageCache has the same setters as NgForageConfig whilst NgForage supports all setters except cacheTime.

Store instances

It is recommended to declare NgForage and/or NgForageCache in providers if you're not using the default configuration. The running configuration hash is used to create and reuse drivers (e.g. different IndexedDB databases), therefore setting it on a shared instance might have unintended side-effects.

Defining a Driver

  1. Define a driver as described in the localForage docs
  2. Plug it in, either directly through localForage or through NgForageConfig:
import {NgModule} from "@angular/core";
import {NgForageConfig, NgForageModule} from "ngforage";
import * as localForage from 'localforage';

// Your driver definition
const myDriver: localForage.LocalForageDriver = {/*...*/};

// Define it through localForage
localForage.defineDriver(myDriver)
  .then(() => console.log('Defined!'))
  .catch(console.error);

@NgModule({
  imports: [
    NgForageModule
  ]
})
export class DemoModule {

  constructor(conf: NgForageConfig) {
    // Or through NgForageConfig
    conf.defineDriver(myDriver)
      .then(() => console.log('Defined!'))
      .catch(console.error);
  }
}