What is the correct way to share the result of an Angular Http network call in RxJs 5?

前端 未结 21 1279
广开言路
广开言路 2020-11-21 06:11

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return          


        
21条回答
  •  清酒与你
    2020-11-21 06:30

    I found a way to store the http get result into sessionStorage and use it for the session, so that it will never call the server again.

    I used it to call github API to avoid usage limit.

    @Injectable()
    export class HttpCache {
      constructor(private http: Http) {}
    
      get(url: string): Observable {
        let cached: any;
        if (cached === sessionStorage.getItem(url)) {
          return Observable.of(JSON.parse(cached));
        } else {
          return this.http.get(url)
            .map(resp => {
              sessionStorage.setItem(url, resp.text());
              return resp.json();
            });
        }
      }
    }
    

    FYI, sessionStorage limit is 5M(or 4.75M). So, it should not be used like this for large set of data.

    ------ edit -------------
    If you want to have refreshed data with F5, which usesmemory data instead of sessionStorage;

    @Injectable()
    export class HttpCache {
      cached: any = {};  // this will store data
      constructor(private http: Http) {}
    
      get(url: string): Observable {
        if (this.cached[url]) {
          return Observable.of(this.cached[url]));
        } else {
          return this.http.get(url)
            .map(resp => {
              this.cached[url] = resp.text();
              return resp.json();
            });
        }
      }
    }
    

提交回复
热议问题