angular async cache
Table of contents
About
A simple utility to help with caching of promises and observables to enable an easy offline first approach in angular 2.0+ apps
Installation
Install through npm:
npm install --save angular-async-cache
Sample usage
import { NgModule, Component, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { AsyncCache, LocalStorageDriver, MemoryDriver, AsyncCacheModule, AsyncCacheOptions, CachedHttp } from 'angular-async-cache';
export function asyncCacheOptionsFactory(): AsyncCacheOptions {
return new AsyncCacheOptions({
driver: new LocalStorageDriver(),
fromCacheAndReplay: true
});
}
@NgModule({
imports: [
AsyncCacheModule.forRoot({
provide: AsyncCacheOptions,
useFactory: asyncCacheOptionsFactory
})
]
})
class MyModule {}
@Injectable()
class CarService {
constructor(
private http: Http,
private asyncCache: AsyncCache,
private memoryDriver: MemoryDriver
) {}
getCars(): Observable<Car[]> {
const cars$: Observable<Car[]> = this.http.get('/cars').map(res => res.json());
return asyncCache.wrap(cars$, '/cars', {
driver: this.memoryDriver,
});
}
}
@Component({
template: `
<div *ngFor="let car of cars | async">
{{ car.model }}
</div>
`
})
class MyComponent {
cars: Observable<Car[]>;
constructor(carService: CarService) {
this.cars = carService.getCars();
}
}
@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').map(res => res.json());
}
}
@Injectable()
class CarService {
constructor(private cachedHttp: CachedHttp) {}
getCars(): Observable<Car[]> {
return this.cachedHttp.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
- Bump the version in package.json (once the module hits 1.0 this will become automatic)
npm run release
License
MIT