Coder Social home page Coder Social logo

mattlewis92 / angular-async-cache Goto Github PK

View Code? Open in Web Editor NEW
20.0 5.0 3.0 364 KB

A simple utility to help with caching of promises and observables to enable an easy offline first approach in angular 6+ apps

License: MIT License

TypeScript 100.00%

angular-async-cache's Introduction

angular async cache

Build Status npm version devDependency Status GitHub issues GitHub stars GitHub license

Table of contents

About

A simple utility to help with caching of promises and observables to enable an easy offline first approach in angular 6+ apps

Demo

There is a demo app here that shows the power of this library. Subscribe to some TV shows, turn off your internet and refresh the page and everything should still work (static assets are handled by the fantastic webpack offline plugin)

Installation

Install through npm:

npm install --save angular-async-cache

Examples

This setup will first emit the cached data (for faster load times + offline first support), then will find the live data, re-emit it and update the cache for future requests

import { NgModule, Component, Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import {
  AsyncCache,
  LocalStorageDriver,
  MemoryDriver,
  AsyncCacheModule,
  AsyncCacheOptions,
  CachedHttp
} from 'angular-async-cache';

export function asyncCacheOptionsFactory(): AsyncCacheOptions {
  return new AsyncCacheOptions({
    // Default cache driver to use. Default in memory.
    // You can also roll your own by implementing the CacheDriver interface
    driver: new LocalStorageDriver(),

    // this is the special sauce - first emit the data from localstorage,
    // then re-fetch the live data from the API and emit a second time.
    // The async pipe will then re-render and update the UI. Default: false
    fromCacheAndReplay: true
  });
}

// declare in your module
@NgModule({
  imports: [
    HttpClientModule,
    // this configures the default options. Just using `AsyncCacheModule.forRoot()` will use
    // the defaults of an in memory cache and not replaying from the api
    AsyncCacheModule.forRoot({
      provide: AsyncCacheOptions,
      useFactory: asyncCacheOptionsFactory
    })
  ]
})
class MyModule {}

// finally use with the async pipe in your components template
@Component({
  template: `
    <div *ngFor="let car of cars | async">
      {{ car.model }}
    </div>
  `
})
class MyComponent {
  cars: Observable<Car[]>;

  constructor(private cachedHttp: CachedHttp) {
    // only the get method is supported (as other http verbs are destructive)
    // The second argument can be any options you would pass to a normal http get call
    // The third argument is a `AsyncCacheOptions` subset
    this.cars = this.cachedHttp.get('/cars');
  }
}

There is also a lower level AsyncCache service that you can use to manually control caching of observables or promises

@Injectable()
class CarService {
  constructor(
    private http: Http,
    private asyncCache: AsyncCache,
    private memoryDriver: MemoryDriver
  ) {}

  getCars(): Observable<Car[]> {
    const cars$: Observable<Car[]> = this.http.get('/cars');
    return asyncCache.wrap(cars$, '/cars', {
      driver: this.memoryDriver // override the default and cache the data in memory
    });
  }
}

There is also a pipe you can use to instantiate the caching in your template

@Component({
  template: `
    <div *ngFor="let car of cars | asyncCache:'/cars' | async">
      {{ car.model }}
    </div>
  `
})
class MyComponent {
  cars: Observable<Car[]>;

  constructor(http: Http) {
    this.cars = http.get('/cars');
  }
}

Development

Prepare your environment

  • Install Node.js and NPM (should come with)
  • Install local dev dependencies: npm install while current directory is this repo

Development server

Run npm start to start a development server on port 8000 with auto reload + tests.

Testing

Run npm test to run tests once or npm run test:watch to continually run tests.

Release

npm run release

License

MIT

angular-async-cache's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

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.