Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - best way to cache http response

I have a lot of services with requests to rest service and I want to cache data receive from server for further usage. Could anyone tell what is the best way to cash response?

like image 527
S.Kos Avatar asked Oct 04 '17 14:10

S.Kos


2 Answers

You will find multiple answers here: Angular 2 cache observable http result data

I would recommend to build simple class Cacheable<> that helps managing cache of data retrieved from http server or other any other source:

declare type GetDataHandler<T> = () => Observable<T>;

export class Cacheable<T> {

    protected data: T;
    protected subjectData: Subject<T>;
    protected observableData: Observable<T>;
    public getHandler: GetDataHandler<T>;

    constructor() {
      this.subjectData = new ReplaySubject(1);
      this.observableData = this.subjectData.asObservable();
    }

    public getData(): Observable<T> {
      if (!this.getHandler) {
        throw new Error("getHandler is not defined");
      }
      if (!this.data) {
        this.getHandler().map((r: T) => {
          this.data = r;
          return r;
        }).subscribe(
          result => this.subjectData.next(result),
          err => this.subjectData.error(err)
        );
      }
      return this.observableData;
    }

    public resetCache(): void {
      this.data = null;
    }

    public refresh(): void {
      this.resetCache();
      this.getData();
    }

}

Usage

Declare Cacheable<> object (presumably as part of the service):

list: Cacheable<string> = new Cacheable<string>();

and handler:

this.list.getHandler = () => {
// get data from server
return this.http.get(url)
.map((r: Response) => r.json() as string[]);
}

Call from a component:

//gets data from server
List.getData().subscribe(…)

More details and code example are here: http://devinstance.net/articles/20171021/rxjs-cacheable

like image 134
yfranz Avatar answered Nov 17 '22 21:11

yfranz


You can also use http interceptors with angular 4+ versions. A very detailed and straight-forward implementation with explanation-https://www.concretepage.com/angular/angular-caching-http-interceptor

like image 41
rohan thakur Avatar answered Nov 17 '22 20:11

rohan thakur