我正在尝试将服务工作者添加到我们现有的angular(5.2,CLI 1.7.1)应用程序中 . 我做了我想做的一切:
-
我创建了ngsw-config.json
-
我运行
ng set apps.0.serviceWorker=true
命令,所以我在angular-cli.json中有"serviceWorker": true,
. -
我已安装
"@angular/service-worker": "5.2.9"
-
我添加到app.module.ts:
import { ServiceWorkerModule } from '@angular/service-worker';
imports: [
...
ServiceWorkerModule.register('/ngsw-worker.js',
{ enabled: environment.production }),
]
我甚至试图将这段代码(我在某处找到解决方案)添加到main.ts中
platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
if ('serviceWorker' in navigator && environment.production) {
navigator.serviceWorker.register('/ngsw-worker.js');
}
}).catch(err => console.log(err));
But I got this error:
未捕获(承诺)DOMException:无法注册ServiceWorker:脚本具有不受支持的MIME类型('text / html') . 错误:未捕获(在承诺中):SecurityError:无法注册ServiceWorker:脚本具有不受支持的MIME类型('text / html') . at resolvePromise(polyfills.3e9ea997ddae46e16c09.bundle.js:1)
在我自己的个人小应用程序中,我做了同样的工作,没有任何错误 . 我们遇到此错误的应用程序非常庞大 . 有很多第三方库 . 我读过它们可能有问题 .
你能帮我吗?
Also, I was checking my own application to find possible differences, which I didn't but I looked at network tab in devtools and I've noticed that the files which should be cached by service worker are always loaded. Is it a correct behaviour please?
1 回答
这可能是由于缺少ngsw-worker.js文件引起的 .
可能你正在使用HTML5 pushState style URLs,并且你有configured your web server来返回服务器上实际不存在的任何文件或文件夹的索引页面(通常是index.html) . 如果ngsw-worker.js实际上不存在,则Web服务器会将请求重定向到ngsw-worker.js到index.html(因此MIME类型为"text/html") .
运行时,通常会将ngsw-worker.js文件复制到dist文件夹中