Angular API响应后更新缓存时角度服务工作者更新视图

Angular API响应后更新缓存时角度服务工作者更新视图,angular,angular-service-worker,Angular,Angular Service Worker,我正在使用Angular service worker缓存API响应 我使用以下配置缓存API:- "dataGroups":[ { "name":"services", "urls":[ "apiUrl" ], "cacheConfig": { "maxSize": 1,

我正在使用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的网络策略)。

将服务中的缓存数据设为
行为主体
类型的对象。在视图所在的组件中订阅它。在订阅回调中更新视图。 比如说,

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();
}
从'@angular/common/http'导入{HttpClient};
从“rxjs”导入{BehaviorSubject};
从“rxjs/operators”导入{tap};
//apiService.service.ts
cacheData=新行为主体(/*初始值*/)
构造函数(专用http:HttpClient){
}
缓存(){
返回cacheData.asObservable();
}
api_请求(){
//我希望yor GET请求返回的对象与您的\u缓存\u对象类型完全相同
//否则,请将响应解析为\u缓存\u对象
返回这个.http.get(“地址”)。
烟斗(
点击(响应=>{
this.cacheData.next(data);//cacheData现在将数据作为最后发出的对象保存
}));
}
//app.component.ts
恩戈尼尼特(){
//API调用返回响应后的更新视图
this.apiService.cache.subscribe(数据=>{
//更新视图中使用的属性
});
此.apiService.api_请求().subscribe();
}
Stackblitz应用程序。

1。看看ngrx2。如果在我们的组件中使用@Input()和changeDetection:OnPush,那么您必须重新输入对象/数组(array.from(…)/object.assign({},我们的对象)/新的\u类\u名称(DATA))数据,并将其分配给组件3。当加载新数据时,您可以从服务中发出事件,并从组件订阅该事件,然后刷新组件数据。请研究一下:如何获取服务人员存储的缓存数据?您可以创建stackblitz或plunker吗?通过此示例,这将非常有用。