import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { concatAll, map, Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CacheService {
  public cache = new Map<string, any>()

  constructor(private http: HttpClient) { }

  /**
   * 先从缓存中加载数据，然后再刷新, 主要解决回退时数据加载慢导致scroll不起作用的问题.
   * @param url 
   * @param params 
   * @returns 
   */
  get(url: string, params?: HttpParams): Observable<any> {
    let key = params ?  `url-${JSON.stringify(params)}` : url;
    let refresh = this.http.get(url, { params }).pipe(map(resp => {
      this.cache.set(key, resp);
      return resp;
    }));
    if (this.cache.has(key)) {
      let old = this.cache.get(key);
      return of(of(old), refresh).pipe(concatAll());
    } else {
      return refresh;
    }
  }



}
