12

更新到 Angular 5 后,我尝试将服务人员添加到我的项目中,但遇到了一些问题。我将导入添加到 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 中的 service workers 很清楚。怎么了?可能是这个标志破坏了它--aot=false --build-optimizer=false?

4

1 回答 1

31

在同时导入 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));
于 2018-02-11T18:20:06.577 回答