How to cache APIs like Google Maps while using Service Workers

瘦欲@ 提交于 2019-12-04 13:16:39
Jeff Posnick

You can include logic in your fetch handler that examines event.request.url and takes whatever arbitrary action you'd like to return a Response from a cache, or even create a new Response on the fly.

Something along the lines of:

self.addEventListener('fetch', function(event) {
  if (event.request.url.indexOf('https://maps.googleapi.com/js') == 0) {
    event.respondWith(
      // Handle Maps API requests in a generic fashion,
      // by returning a Promise that resolves to a Response.
    );
  } else {
    event.respondWith(
      // Some default handling.
    );
  }
}

Modify the service worker config in ngsw-config.json to cache resources from maps.googleapi.com:

// ngsw-config.json
{
  "assetGroups": [
    "urls": [
      "https://maps.googleapis.com/js*"
    ]
  ]
  ...
}

Reference: https://angular.io/guide/service-worker-config#urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!