0

I searched how to cache XHR in Angular2 and found to use share() method. But the service I created doesn't work I expected to.

// 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, ...]);

What am I missing? (Of course, importing needed classes and interfaces)

Yohsuke Inoda
  • 521
  • 1
  • 6
  • 20

1 Answers1

1

You need to leverage the do operator for this:

getData() {
  if (this.cachedData) {
    return Observable.of(this.cachedData);
  } else {
    return this.http.get(...).map(...)
        .do(data => {
          this.cachedData = data;
        })
  }
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360