Angular 7 pwa / SwPush-推送通知不起作用

时间:2018-12-17 06:53:10

标签: angular push-notification progressive-web-apps angular-service-worker

我正在尝试使用@ angular / pwa link和SwPush在Angular 7中使用推送通知。我无法获得实际的推送通知。 我目前在localhost(通过在执行ng-build之后运行http-server)上工作,而我的api服务器位于云中。 我能够使用swPush.requestSubscription启用订阅,并且订阅已在服务器上成功注册。 在Chrome浏览器中,所有api调用都被服务工作者本身阻止(失败:来自服务工作者),而在Firefox中,没有错误,但没有出现推送消息。

我在下面添加了相关的代码段。由于没有报告具体错误,因此我无法继续进行。

请告知如何使它工作并显示通知。

app.module.ts

import {PushNotificationService} from 'core';
import { ServiceWorkerModule } from '@angular/service-worker';
@NgModule({
declarations: [
    AppComponent,

],
imports: [

    ServiceWorkerModule.register('ngsw-worker.js', { enabled: true })
],
providers: [
    PushNotificationService,
],
exports: [],
bootstrap: [AppComponent]
   })
 export class AppModule {
  }


   app.component.ts
export class AppComponent  {

constructor(private pushNotification :PushNotificationService,
private swPush : SwPush){
this.swPush.messages.subscribe(notification => {
          const notificationData: any = notification;
     const options = {
      body: notificationData.message,
      badgeUrl: notificationData.badgeUrl,
      icon: notificationData.iconUrl
    };
    navigator.serviceWorker.getRegistration().then(reg => {
      console.log('showed notification');
      reg.showNotification(notificationData.title, options).then(res => {
        console.log(res);
      }, err => {
        console.error(err);
      });
    });
  });

}
     isSupported() {
      return this.pushNotification.isSupported;
   }

  isSubscribed() {
  console.log(' ****** profile component' + this.swPush.isEnabled);
  return this.swPush.isEnabled;
}

 enablePushMessages() {
  console.log('Enable called'); 
  this.pushNotification.subscribeToPush();

}

 disablePushMessages(){
  // code for unsubsribe
  }
}

push.notification.service

 export class PushNotificationService {
 public isSupported = true;
 public isSubscribed = false;
 private swRegistration: any = null;
  private userAgent = window.navigator.userAgent;
 constructor(private http: HttpClient, private swPush: SwPush) {
   if ((this.userAgent.indexOf('Edge') > -1) || 
   (this.userAgent.indexOf('MSIE') > -1) || (this.userAgent.indexOf('.Net') 
    > -1)) {
      this.isSupported = false;
    }
}

subscribeToPush() {
// Requesting messaging service to subscribe current client (browser)
  let publickey = 'xchbjhbidcidd'
   this.swPush.requestSubscription({
    serverPublicKey: publickey
   }).then(pushSubscription => {
     console.log('request push subscription ', pushSubscription);
     this.createSubscriptionOnServer(pushSubscription);
      })
  .catch(err => {
    console.error(err);
  });
}

 createSubscriptionOnServer(subscription) {
  let urlName = 'api/user/notificationSubscription';
  let params;
  params = {
  endpoint: subscription.endpoint,
   };
this.http.put<any>(urlName, params, httpOptions).pipe(
  tap((res) => {
    if (res.data) {
      if (res.data.success) {
        alert('Success')
      } else {
        alert('error')
      }
    }
  }));
 }
 }

3 个答案:

答案 0 :(得分:2)

要使服务工作者正常工作,您需要使用--prod进行编译。 尝试使用ng build --prod

进行编译

答案 1 :(得分:1)

您需要安装Angular CLI,用于服务工作者的PWA,用于生成VAPID密钥的webpush和用于运行模拟服务器的http-server。您可以通过运行:

npm i -g @angular/cli --save
ng add @angular/pwa --save
npm i webpush --save
npm i http-server -g --save

现在您需要使用webpush生成VAPID密钥对,以便在前端和后端使用它

web-push generate-vapid-keys --json

将生成的配对保存在某处。使用app.component.ts中的以下代码向用户请求订阅

import { Component } from '@angular/core';
import { SwPush } from '@angular/service-worker';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(swPush: SwPush) {
if (swPush.isEnabled) {
  swPush.requestSubscription({
      serverPublicKey: VAPID_PUBLIC_KEY
    })
    .then(subscription => {
      // send subscription to the server
    })
    .catch(console.error);
}
  }
}

VAPID_PUBLIC_KEY是您之前获得的公共密钥。

将此添加到您的Angular项目中的node_modules/@angular/service-worker/ngsw-worker.js

this.scope.addEventListener('notificationclick', (event) => {
            console.log('[Service Worker] Notification click Received. event:%s', event);
            event.notification.close();
            if (clients.openWindow && event.notification.data.url) {
                event.waitUntil(clients.openWindow(event.notification.data.url));
            }
        });

您可以输入上面的代码,在文件内的下一行>该行的编号为1893。

this.scope.addEventListener('notificationclick', (event) => ..

您必须再次构建dist才能使其正常工作。 现在使用

ng build --prod

生成dist并使用

http-server ./dist/YOUR_DIST_FOLDER_NAME -p 9999

在后端文件中,您应该是这样的。

const express = require('express');
const webpush = require('web-push');
const cors = require('cors');
const bodyParser = require('body-parser');

const PUBLIC_VAPID = 'PUBLIC_VAPID_KEY';
const PRIVATE_VAPID = 'PRIVATE_VAPID_KEY';

const fakeDatabase = [];

const app = express();

app.use(cors());
app.use(bodyParser.json());

webpush.setVapidDetails('mailto:you@domain.com', PUBLIC_VAPID, PRIVATE_VAPID);

app.post('/subscription', (req, res) => {
       const subscription = req.body;
      fakeDatabase.push(subscription);
    });

app.post('/sendNotification', (req, res) => {
  const notificationPayload = {
    {"notification":
       { 
        "body":"This is a message.",
        "title":"PUSH MESSAGE",
        "vibrate":300,100,400,100,400,100,400],
        "icon":"ICON_URL",
        "tag":"push demo",
        "requireInteraction":true,
        "renotify":true,
        "data":
          { "url":"https://google.com"}
       }
    }
  };

  const promises = [];
  fakeDatabase.forEach(subscription => {
    promises.push(webpush.sendNotification(subscription, 
JSON.stringify(notificationPayload)));
  });
  Promise.all(promises).then(() => res.sendStatus(200));
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

您可以在网址内输入网址,点击通知后,您的推送通知将打开给定的链接并将其聚焦在浏览器中。

答案 2 :(得分:0)

在我的情况下, Windows 计算机上的通知和操作设置中禁用了 Google Chrome通知