Angular Service Worker,缓存api调用离线应用

时间:2018-01-24 10:09:52

标签: javascript angular service-worker angular5 angular-service-worker

我试图通过API请求使角色工作的服务工作者。 我希望该应用离线工作,我已经完成了以下配置:

    {
        "name": "api",
        "urls": ["https://x.com/**"],
        "cacheConfig": {
            "strategy": "performance",
            "maxSize": 20,
            "maxAge": "365d",
            "timeout": "5s"
        }
    }

以下是当我离线时xhr标签的样子:

enter image description here

这是用户请求的内容:

enter image description here

正如您所看到的那样,API要求用户不要解决。

这就是user在线时的响应:

enter image description here

4 个答案:

答案 0 :(得分:3)

试试这个:

  • 转到您的应用程序标签 - >清除存储 - >清除网站数据。
  • 从此处更改DataGroups数组:

    {
        "name": "api",
        "urls": ["https://x.com/**"],
        "cacheConfig": {
            "strategy": "performance",
            "maxSize": 20,
            "maxAge": "365d",
            "timeout": "5s"
        }
    }
    

对此:

"dataGroups": [
    {
      "name": "api-performance",
      "urls": [
        "/user" //<=========== I know you want all API calls to be cached, but try this first and see
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 100,
        "maxAge": "3d"
      }
    }
  ]
  • PROD
  • 中保存并构建您的应用
  • 第一次访问该页面。
  • 禁用网络
  • 刷新页面

答案 1 :(得分:0)

要离线处理Api数据,您必须使用离线存储(即在初始API调用后在Web浏览器中存储数据),最近我在我的应用程序中使用了Local Forage。找到以下链接:

https://github.com/Alorel/ngforage#types-and-polyfills

https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/offline-for-pwa

答案 2 :(得分:0)

如果您使用的是“策略”:“性能”,请删除超时属性

答案 3 :(得分:-2)

“数据组”:[ {

        "name": "TestApi",
        "urls": [
            "https://api.chucknorris.io/jokes/random",
            "https://localhost:4377/api/home/getNames/"
        ],
        "cacheConfig": {
            "strategy": "freshness",
            "maxSize": 20,
            "maxAge": "1h",
            "timeout": "5s"
        }
    },
    {
        "name": "TestAPI",
        "urls": [
            "https://localhost:4377/api/test/getList",
            "https://localhost:4377/api/template/start/"
        ],
        "cacheConfig": {
            "strategy": "performance",
            "maxSize": 20,
            "maxAge": "2h",
            "timeout": "5s"
        }
    }
]