【问题标题】:Prefetch data from all APIs with Angular service worker使用 Angular Service Worker 从所有 API 中预取数据
【发布时间】:2020-05-26 08:52:12
【问题描述】:

我想从数据组数组中定义的所有 API 中预取和缓存数据。即使用户没有访问相关页面或执行进行这些调用的功能,也应该获取和缓存数据。在我的情况下,在不预取数据的情况下获得离线支持是没有用的。

有没有办法像 Angular 为资产提供的那样预取 API 数据,还是我需要对我在数据组中指定的所有 API 进行一些虚拟 API 调用?

TIA

【问题讨论】:

    标签: angular rest service-worker progressive-web-apps angular-service-worker


    【解决方案1】:

    我部署了一个示例服务来解释如何只调用一次服务器。

    https://stackblitz.com/edit/stack-overflow-62018147

    • 您必须在构造函数服务中订阅 api 调用,以便在将 this 注入组件时调用它
    • 然后您必须将响应保存在服务内部的私有变量中,如果该变量为空,您可以调用 api rest。在另一种情况下,您可以返回私有变量的内容
        constructor(private http: HttpClient) {
          this.getNations().subscribe(); //The constructor is called when service is injected
        }
    
        public getNations(): Observable<INation []> {
            const url: string = this.backendURL + "places/nations";
            //this is the caching mechanism
            const nations$: Observable<INation []> = (!! this.nations) ? 
              of(this.nations.map((nation: INation) => cloneDeep(nation)))
                .pipe(
                  tap((nations: INation []) => console.log("Returning cached response...", JSON.stringify(nations)))
                ) : 
              this.http.get<INation []>(url);
            //------------------------
            return nations$.pipe(
                tap((nations: INation []) => this.nations = nations),
                catchError(() => {
                  console.error("Http Error, returning MOCK. If you see in network, this is called only one time.");
                  this.nations = cloneDeep(this.nations_MOCK);
                  return of(this.nations);
                })
            );
        }
    

    【讨论】:

    • 嗨 Lolbreaker,您是否介意在此处添加相关代码 sn-ps,以便任何访问者都能立即看到 :)
    猜你喜欢
    • 2020-11-28
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-12-11
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多