I created this decorator for cashing requests in my angular services.
npm i --save cache-observable
Need add @CacheObservable(ms)
before a function that return ConnectableObservable
(angular http.get()
or Observable.ajax()
), where ms
is cache time in milliseconds.
// book.service.ts
// ...
import CacheObservable from 'cache-observable';
@Injectable()
export class BookService {
private path: string = '/books';
constructor(private api: apiService) {
}
@CacheObservable(60 * 1000) // 1 min cache
getBook(id: string): Observable<Book> {
return this.api.get(`${this.path}/${id}`);
}
// ...
}
- Call a function with
@CacheObservable()
decorator; - The Decorator lib check, if a storage have the observable entry then return it;
- If the storage haven't a entry of a called function, then the Decorator lib create new entry in the storage;
- The new entry observable has been chained with next functions:
- publishReplay(1, ms) // publish one item for
ms
milliseconds - refCount() // check all subscribers
- take(1) // take one
- Return the entry.
MIT