【问题标题】:Angular service worker update view when cache is updated after API responseAPI响应后更新缓存时的角度服务工作者更新视图
【发布时间】:2020-02-27 18:57:03
【问题描述】:

我正在使用 Angular Service Worker 来缓存我的 API 响应。

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

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

它第一次缓存服务调用的响应,第二次显示缓存中的数据并并行调用 API。在 API 响应之后,它只更新缓存。 但是我也想在更新缓存时更新我的​​视图。 现在我必须重新加载我的页面以查看更新的数据,当 API 调用返回响应而不重新加载页面时,有什么方法可以更新视图上的数据(缓存然后网络策略与角度服务工作者)。

【问题讨论】:

  • 1.看看ngrx
  • 2.如果在我们的组件中你使用 @Input() 和 changeDetection: OnPush 你必须重新初始化对象/数组 (Array.from(...) / Object.assign({}, OUR_OBJECT) / new YOUR_CLASS_NAME(DATA)) 数据你给什么到你的组件
  • 3.您可以在加载新数据时从服务发出事件,并从组件订阅该事件,然后刷新组件数据

标签: angular angular-service-worker


【解决方案1】:

将服务中的缓存数据设为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

【讨论】:

  • 如何获取 service worker 存储的缓存数据?
  • 你能用这个例子创建stackblitz或plunker吗,这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多