Angular 7 Service Worker设置-ngsw-worker.js注册错误

时间:2019-03-27 16:59:44

标签: angular angular6 service-worker angular7 service-worker-events

问题:

当前获得ERR_INVALID_RESPONSE和/ngsw-config.json:-Infinity 解析器错误:网络流量中的ngsw-worker.js文件。

请参见下图:

enter image description here

技术:Angular CLI和Angular版本7。

我所做的事情

我已将这些标签添加到index.html头中:

  <link rel="manifest" src="manifest.json">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="theme-color" content="#2c3e50">

我的Manifest.json:

{
  "short_name": "test",
  "name": "test.co.uk",
  "start_url": "/",
  "background_color": "#2c3e50",
  "display": "standalone",
  "orientation": "portrait",
  "theme_color": "#2c3e50",
  "icons": []
}

我的angular.json文件:

"serviceWorker": true

针对:

“建筑师”:{         “内部版本”:{           “ builder”:“ @ angular-devkit / build-angular:browser”,           “ options”:{“ serviceWorker”:true

我的Main.ts文件:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

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

我的ngsw-worker.js文件:

{
  "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-freshness",
    "urls": [
      "/new"
    ],
    "cacheConfig": {
      "maxSize": 100,
      "maxAge": "1h",
      "timeout": "10s",
      "strategy": "freshness"
    }
  }, {
    "name": "api-performance",
    "urls": [
      "/"
    ],
    "cacheConfig": {
      "maxSize": 100,
      "maxAge": "1d",
      "strategy": "performance"
    }
  }]
}

2 个答案:

答案 0 :(得分:0)

我在chrome devtools中看到您的登台站点正在尝试从文件ngsw-config.json而不是ngsw-worker.js加载服务工作者。可能是您混合了这两个文件吗?

chorme dev tools of https://behired-staging.firebaseapp.com/

service-worker始终会向js文件(通常为ngsw-worker.js)注册,然后service worker从例如Windows Server 2003中获取配置。 ngsw-config.json

因此,“网络”标签中的加载顺序应如下所示:

load order service worker

答案 1 :(得分:0)

如果您将其托管在IIS中,则应在web.config中为json类型添加MimeType-

例如:

   
<configuration>
  <system.webServer>
     <staticContent>
        <mimeMap fileExtension=".json" mimeType="application/json" />
     </staticContent>
  </system.webServer>
</configuration>