API响应后更新缓存时,Angular service worker更新视图



我正在使用Angular服务工作者缓存我的API响应。

我正在使用以下配置缓存API:-

"dataGroups":[
{
"name":"services",
"urls":[
"apiUrl"
],
"cacheConfig": {
"maxSize": 1,
"maxAge": "1d",
"timeout": "0s",
"strategy": "freshness"
}
}
]

第一次它缓存服务调用的响应,第二次它显示缓存中的数据并并行进行API调用。API响应后,它只更新缓存。但我也希望在缓存更新时更新我的视图。现在我必须重新加载我的页面以查看更新的数据,当API调用返回响应而不重新加载页面时,有没有任何方法可以更新视图中的数据(使用angular service worker缓存然后网络策略(。

使服务中的缓存数据成为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();
}

Stacklitz应用程序。https://stackblitz.com/edit/angular-6iujsm

最新更新