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)