Angular 5 Service Worker无法正常工作

时间:2018-02-10 16:53:13

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

我尝试在更新为angular 5之后将service worker添加到我的项目中并遇到一些问题。我将导入添加到app.module.ts:

import {ServiceWorkerModule} from '@angular/service-worker';
import {environment} from '../environments/environment';
...
environment.production ? ServiceWorkerModule.register('/ngsw-worker.js') : [],

执行$ ng set apps.0.serviceWorker=true以允许项目中的服务工作者

生成配置:

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/index.html"
        ],
        "versionedFiles": [
          "/*.bundle.css",
          "/*.bundle.js",
          "/*.chunk.js"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**"
        ]
      }
    }
  ],
  "dataGroups": [
    {
      "name": "api-performance",
      "urls": [
        "/",
        "/main",
        "/login",
        "/select-content"
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 100,
        "maxAge": "3d"
      }
    }
  ]
}

并表明:

{
  "name": "App",
  "short_name": "App",
  "start_url": "/login",
  "theme_color": "#00a2e8",
  "background_color": "#00a2e8",
  "display": "standalone",
 "icons": [
  {
   "src": "assets\/icons\/android-icon-36x36.png",
   "sizes": "36x36",
   "type": "image\/png",
   "density": "0.75"
  },
  {
   "src": "assets\/icons\/android-icon-48x48.png",
   "sizes": "48x48",
   "type": "image\/png",
   "density": "1.0"
  },
  {
   "src": "assets\/icons\/android-icon-72x72.png",
   "sizes": "72x72",
   "type": "image\/png",
   "density": "1.5"
  },
  {
   "src": "assets\/icons\/android-icon-96x96.png",
   "sizes": "96x96",
   "type": "image\/png",
   "density": "2.0"
  },
  {
   "src": "assets\/icons\/android-icon-144x144.png",
   "sizes": "144x144",
   "type": "image\/png",
   "density": "3.0"
  },
  {
   "src": "assets\/icons\/android-icon-192x192.png",
   "sizes": "192x192",
   "type": "image\/png",
   "density": "4.0"
  }
 ]
}

然后在生产中构建它:

ng build --prod --aot=false --build-optimizer=false

Http-server在SSL模式下运行,但chrome dev-tools中的lsit服务工作者很清楚。怎么了?可能是这个标志打破了它--aot = false --build-optimizer = false?

1 个答案:

答案 0 :(得分:28)

在模块中注册服务工作者似乎也是一个问题,同时也导入AngularFire2。我找到了解决方法如何在main.ts中注册SW,这是有效的:

platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
  if ('serviceWorker' in navigator && environment.production) {
    navigator.serviceWorker.register('ngsw-worker.js');
  }
}).catch(err => console.log(err));