How to cache APIs like Google Maps while using Service Workers

百般思念 提交于 2019-12-06 08:42:49

问题


Trying to cache Google Maps API response in Service Workers.

Source Code: https://github.com/boopathi/sw-demo-iss/blob/gh-pages/sw.js

Now I'm using all of the URLs that the Maps API would request to, but seems like a bad way, and I'm not able to cache everything, can I cache requests of some type and respond to requests of the same type.

say,

GET maps.googleapi.com/js?param1=value1
#and
GET maps.googleapi.com/js?param2=value2&param3=value3

Is it possible to cache this as 'maps.googleapi.com/js' and while fetching inject last used params ?


回答1:


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.
    );
  }
}



回答2:


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



来源:https://stackoverflow.com/questions/27915193/how-to-cache-apis-like-google-maps-while-using-service-workers

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