我正在使用Angular service worker缓存我的API响应。
我使用以下配置来缓存API:-
"dataGroups":[
{
"name":"services",
"urls":[
"apiUrl"
],
"cacheConfig": {
"maxSize": 1,
"maxAge": "1d",
"timeout": "0s",
"strategy": "freshness"
}
}
]它第一次缓存服务调用的响应,第二次显示缓存中的数据,并并行进行API调用。在API响应之后,它只更新缓存。但我还想在更新缓存时更新我的视图。现在我不得不重新加载我的页面来查看更新的数据,当API调用返回响应而不重新加载页面时,有没有办法更新视图上的数据(使用angular service worker的缓存和网络策略)。
发布于 2020-02-21 19:40:02
使服务中的缓存数据成为BehaviorSubject类型的对象。在视图所在的组件中订阅它。在订阅回调中更新视图。例如,
import { HttpClient} from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';
// apiService.service.ts
cacheData = new BehaviorSubject<your_cache_object>(/*initial_value*/)
constructor(private http: HttpClient) {
}
cache() {
return cacheData.asObservable();
}
api_request() {
// I expect that yor GET request returns exactly object of type your_cache_object
// otherwise, please parse your response as your_cache_object
return this.http.get<your_cache_object>("address").
pipe(
tap(response => {
this.cacheData.next(data); // cacheData now holds data as the last emitted object
}));
}
// app.component.ts
ngOnInit() {
// update view after API call returned a response
this.apiService.cache.subscribe(data => {
// update your properties used in the view
});
this.apiService.api_request().subscribe();
}Stackblitz应用程序。https://stackblitz.com/edit/angular-6iujsm
https://stackoverflow.com/questions/60337374
复制相似问题