简体   繁体   English

使用 Angular service worker 从所有 API 预取数据

[英]Prefetch data from all APIs with Angular service worker

I would like to prefetch and cache data from all the APIs that are defined in the datagroup array.我想从数据组数组中定义的所有 API 中预取和缓存数据。 The data should be fetched and cached even if the user hasn't visited the relvant pages or performed the functions which make those calls.即使用户没有访问相关页面或执行进行这些调用的功能,也应该获取和缓存数据。 Having offline support without prefetching the data is no use in my case.在我的情况下,在不预取数据的情况下获得离线支持是没有用的。

Is there a way to prefetch API data as Angular provides for assets or do I need to make some dummy API calls to all the APIs I have specified in the datagroups?有没有办法预取 API 数据作为 Angular 为资产提供的数据,还是我需要对我在数据组中指定的所有 API 进行一些虚拟 API 调用?

TIA TIA

I deployed a sample service to explain you how to call the server just one time.我部署了一个示例服务来向您解释如何只调用一次服务器。

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

  • You have to subscribe the api call in the constructor service in order to call it when this is injected in the component您必须在构造函数服务中订阅 api 调用,以便在将其注入组件时调用它
  • Then you have to save the response in a private variable inside the service and if this is null you can call the api rest.然后您必须将响应保存在服务内的私有变量中,如果这是 null,您可以调用 api rest。 In the other case you can return the content of the private variable在另一种情况下,您可以返回私有变量的内容
    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);
            })
        );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM