首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >API响应后更新缓存时的Angular service worker更新视图

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

Stack Overflow用户
提问于 2020-02-21 19:06:27
回答 1查看 174关注 0票数 0

我正在使用Angular service worker缓存我的API响应。

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

代码语言:javascript
复制
"dataGroups":[
    {
        "name":"services",
        "urls":[
                   "apiUrl"
               ],
        "cacheConfig": {
                           "maxSize": 1,
                           "maxAge": "1d",
                           "timeout": "0s",
                           "strategy": "freshness"
                       }
        }
]

它第一次缓存服务调用的响应,第二次显示缓存中的数据,并并行进行API调用。在API响应之后,它只更新缓存。但我还想在更新缓存时更新我的视图。现在我不得不重新加载我的页面来查看更新的数据,当API调用返回响应而不重新加载页面时,有没有办法更新视图上的数据(使用angular service worker的缓存和网络策略)。

EN

回答 1

Stack Overflow用户

发布于 2020-02-21 19:40:02

使服务中的缓存数据成为BehaviorSubject类型的对象。在视图所在的组件中订阅它。在订阅回调中更新视图。例如,

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60337374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档