2

I'm using angular universal to pre render a site in the server. Since my app requires to make a few http calls to initialize, I want to implement a cache which will cache the requests made in the server and when requested again in client side, I want to use the cached values instead of re sending the requests again.

My setup:

the http service:

public get(url: string): Promise<any> {

    if (this._cache.has(url)) {
        var retProm =  new Promise(() => {
            return this._cache.get(url);
        });
        return retProm;
    }

    return this.http.get(url, {withCredentials: true}).toPromise()
            .then((data) => {
                if(isNode){
                        this._cache.set(url, data);
                }
                this.extractData(data);
            })
            .catch(this.handleError);
}

My cache service:

 constructor(public _cache: Map<string, any>) {}

 has(key: string | number): boolean {
     let _key = this.normalizeKey(key);
    return this._cache.has(_key);
 }

 set(key: string | number, value: any): void {
    let _key = this.normalizeKey(key);
    this._cache.set(_key, value);
 }

 get(key: string | number): any {
      let _key = this.normalizeKey(key);
      return this._cache.get(_key);
  }

Usage:

this.httpService.get(url).then((data: DataType) => { //usage },(error: any) => console.error(error));}

This works fine when not using the cahce, but returns undefined when it uses the cache. Other way of asking this question would be, lets say if you have a data on a variable, and want to create a replica of http get, by returning the data on the variable as response, without having to change the

caller function, how can it be done?

I am not very familiar with promises in angular2. Any leads would be much appreciated.

Thanks.

sa77
  • 3,563
  • 3
  • 24
  • 37
informeto
  • 162
  • 2
  • 14
  • 1
    http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2-http-network-call-in/36291681#36291681 – Günter Zöchbauer May 05 '17 at 15:12

0 Answers0