【发布时间】:2016-08-26 06:30:17
【问题描述】:
我搜索了如何在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, ...]);
我错过了什么? (当然要导入需要的类和接口)
【问题讨论】:
标签: typescript angular