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

时间:2018-09-26 08:40:01

标签: angular push-notification

我想使用web-push模块和angular service worker推送通知订阅。我已经按照以下链接中的说明进行操作:Angular Push Notifications: a Complete Step-by-Step GuidePush Notifications with Angular & Express,但通知提示并未按应有的方式显示。我检查了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);
}

返回错误:

  

错误:此浏览器禁用或不支持服务人员       在SwPush.push ../ node_modules/@angular/service-worker/fesm5/service-worker.js.SwPush.requestSubscription(service-worker.js:146)       在新的DashboardComponent(dashboard.component.ts:40)       在createClass(core.js:9311)       在createDirectiveInstance(core.js:9186)       在createViewNodes(core.js:10406)       在createRootView(core.js:10320)       在callWithDebugContext(core.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)

预期结果:

result

2 个答案:

答案 0 :(得分:4)

此错误是由于服务工作者不使用ng serve引起的。使用http-server运行,然后运行良好。 如Angular service workers中所说:

  

由于服务不能与服务工作者一起使用,因此必须使用单独的HTTP服务器在本地测试项目。您可以使用任何HTTP服务器

答案 1 :(得分:1)

只需在'AppModule'中将服务工作者设置为在开发环境中工作

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production})

收件人

ServiceWorkerModule.register('ngsw-worker.js', { enabled: true})
相关问题