Django中的Angular Service Worker无法在离线模式下工作

时间:2019-06-24 13:55:38

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

我正在使用 Angular Django 创建 Progressive Web App (PWA)应用程序。更具体地说,我正在使用 @ angular / pwa 程序包,并希望有一个可离线运行的web应用程序。如下所述,使用来自npm的简单 http-服务器 会产生正确的结果,但是将Angular构建部署到Django后,Web应用程序无法在离线模式下工作

设置

我正在使用以下命令构建Angular前端:

ng build --prod --deploy-url="/static/" --base-href="/" --outputHashing=none

然后将文件放入webappBackend/webappBackend/static/中。我还在settings.py中将此目录添加为静态目录。

在运行Django服务器之前我必须解决的问题:

  1. --deploy-url不会在 manifest.webmanifest favicon.ico index.html
  2. 中的“ strong”
<script src="/static/runtime-es2015.js" type="module"></script>
<script src="/static/polyfills-es2015.js" type="module"></script>
<script src="/static/runtime-es5.js" nomodule></script>
<script src="/static/polyfills-es5.js" nomodule></script>
<script src="/static/main-es2015.js" type="module"></script>
<script src="/static/main-es5.js" nomodule></script></body>
  1. --deploy-url不会为 ngsw.json 中的文件添加前缀,因此我必须修复该问题以获取应用程序和资产资源,以及在hashTable中。在这里,我仅包含一些更改以便于阅读:
"urls": [
        "/static/favicon.ico",
        "/static/index.html",
        "/static/main-es2015.js",
        "/static/main-es5.js",
        "/static/polyfills-es2015.js",
        "/static/polyfills-es5.js",
        "/static/runtime-es2015.js",
        "/static/runtime-es5.js",
        "/static/styles.css"
      ]
  1. 我必须添加URL模式以捕获对 ngsw-worker.js 的请求:
url(r'^ngsw-worker.js', 
    (TemplateView.as_view(template_name="ngsw-worker.js",
    content_type='application/javascript', )),
    name='ngsw-worker.js')
  1. 我必须进入 ngsw-worker.js ,并为请求添加一个前缀 / static / > ngsw.json 文件:
const res = yield this.safeFetch(this.adapter.newRequest('/static/ngsw.json?ngsw-cache-bust=' + Math.random()));

服务工作者的注册方式:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })

预期结果与实际结果

预期的行为是该Web应用程序还可以脱机工作。目前,如果我使用

启动http服务器(从npm启动简单的HTTP服务器)
http-server -o

static / 中,它可以按预期运行,甚至可以脱机运行(使用http服务器时,我不需要进行上述修改)。如果我启动Django,则当我离线时,不会加载任何内容。

使用Django,当我离线时, 服务工作者 不会显示在Chrome的开发工具中。 缓存存储 也为空。当我上网时,两者都可以正确显示。

0 个答案:

没有答案