如何在Angular2中缓存XHR

时间:2016-05-01 11:59:18

标签: typescript angular

我搜索了如何在Angular2中缓存XHR并发现使用share()方法。但是我创建的服务并不是我所期望的。

// api_service.interface.ts
interface Api {}
@Injectable()
export class ApiService {
  private caches: { [url: string]: Observable<Api> } = {};

  constructor(private http: Http) {}

  fetch(req: Request): Observable<Api> {
    return this.http.request(req).map((res) => res.json());
  }
  get(url: string): Observable<Api> {
    // Return cached data
    if (url in this.caches) return this.caches[url];

    let req = {
      method: RequestMethod.Get,
      url: url,
    }

    // Store observable object using share() method
    return this.caches[url] = this.fetch(new Request(req)).share();
  }
}

// demo.component.ts
@Component({ ... })
export class DemoComponent {
  public data;

  constructor(private api: ApiService) {
    this.api.get('/test.json').subscribe((data) => this.data = data);
  }
}

// boot.ts
import { ... } from ...
bootstrap(RouterComponent, [ApiService, ...]);

我错过了什么? (当然,导入所需的类和接口)

1 个答案:

答案 0 :(得分:1)

您需要利用do运算符:

getData() {
  if (this.cachedData) {
    return Observable.of(this.cachedData);
  } else {
    return this.http.get(...).map(...)
        .do(data => {
          this.cachedData = data;
        })
  }
}