【发布时间】:2017-11-24 17:06:34
【问题描述】:
我正在尝试在 Angular 应用程序中为 http 服务实现缓存。
我的服务代码 countriesService
public get(): Observable<any> {
return this.http.get(`/countries`, {})
.map(res => res.json())
.publishReplay(1)
.refCount();
}
在组件CountriesComponent中,我有
ngOnInit() {
this.countriesService.get()
.subscribe(res => {
this.countries = res.countries;
});
}
我正在路由配置中加载组件
const appRoutes: Routes = [
{ path: 'countries', component: CountriesComponent },
{ path: 'cities', component: CitiesComponent },
];
每次我从城市返回国家/地区时,都会看到对 => /国家的请求。它不应该触发请求,因为它应该被缓存(这就是它在 angular 1.x 中使用 promises 的工作方式),但不适用于 angular 4 和 rxJs。
【问题讨论】:
-
会不会只是因为它在 ngOnInit 中被调用,因此当你从城市到国家时它又会启动?
-
是的,我认为这就是它发生的原因。但是根据我对 ng 1.x 和 promise $http 的经验,在我手动清除缓存或修改请求 url 之前,不应该有进一步的 ngOnInit 请求