Angular 6-“服务工作者被禁用或不支持”错误

Bro*_*Eye 8 push-notification angular

我要推通知订阅与web-push模块angular service worker。我已经按照以下链接中的说明进行操作:Angular Push Notifications:完整的分步指南Angular&Express的Push Notifications,但通知提示并未如期显示。我检查了该swPush对象,发现它没有启用,而且我什至不知道为什么我angular/pwa完全按照这些链接所说的那样遵循安装说明。希望这里有人能帮忙。非常感谢!

我使用自己的Nodejs服务器而不是http-server模块来运行应用程序。

这是我的推送订阅代码:

readonly VAPID_PUBLIC_KEY =
'BIfDkegCvhzctX06rYvwQImhbfAymWYE3wtcog9E4Zj7LOgX6TQFS6fZSqLCt01zBZtc1-jSwpZrZEmTQ2i95V8'; // key generated with web-push

 constructor(
   private user: UserService,
   private httpClient: HttpClient,
   private router: Router,
   private auth: AuthService,
   private swPush: SwPush
 ) {
     this.swPush.requestSubscription({
       serverPublicKey: this.VAPID_PUBLIC_KEY
     })
     .then(subcription => {
       console.log('Send ' + subcription + ' to server');
     })
     .catch(console.error);
}
Run Code Online (Sandbox Code Playgroud)

返回错误:

错误:服务工作者已禁用或不受此浏览器支持,位于新的SwPush.push ../ node_modules/@angular/service-worker/fesm5/service-worker.js.SwPush.requestSubscription(service-worker.js:146)的createClass(core.js:9311)的createClass(core.js:9186)的createClass(core.js:9186)的createClass Nodes(core.js:10406)的createRootView(core.js:10320)的createClass(core.js:1031)的DashboardComponent(dashboard.component.ts:40) .js:11351),位于Object.debugCreateRootView [作为createRootView](core.js:10838),位于ComponentFactory_.push ../ node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create(core.js:8666)在ComponentFactoryBoundToModule.push ../ node_modules/@angular/core/fesm5/core.js.ComponentFactoryBoundToModule.create(core.js:3315)

预期结果:

结果

use*_*102 15

只需将服务工作人员设置为在“AppModule”中的开发环境中工作

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production})
Run Code Online (Sandbox Code Playgroud)

ServiceWorkerModule.register('ngsw-worker.js', { enabled: true})
Run Code Online (Sandbox Code Playgroud)


Bro*_*Eye 8

导致此错误的原因是服务人员无法使用ng serve。运行,http-server然后工作正常。正如Angular服务人员所说:

由于ng serve不适用于服务人员,因此您必须使用单独的HTTP服务器在本地测试您的项目。您可以使用任何HTTP服务器

  • ..除了在本地主机上 (3认同)
  • ..并且服务人员也只能使用https (2认同)