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

ram*_*hna 5 push-notification progressive-web-apps angular angular-service-worker

我正在尝试使用@ angular/pwa 链接 和使用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
  }
}
Run Code Online (Sandbox Code Playgroud)

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')
      }
    }
  }));
 }
 }
Run Code Online (Sandbox Code Playgroud)

cyp*_*unk 7

您需要安装 Angular CLI、用于 Service Worker 的 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
Run Code Online (Sandbox Code Playgroud)

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

web-push generate-vapid-keys --json
Run Code Online (Sandbox Code Playgroud)

将生成的对保存在某处。在 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);
}
  }
}
Run Code Online (Sandbox Code Playgroud)

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));
            }
        });
Run Code Online (Sandbox Code Playgroud)

您可以在文件中找到以下行的位置输入上面的代码>它将在第 1893 行。

this.scope.addEventListener('notificationclick', (event) => ..
Run Code Online (Sandbox Code Playgroud)

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

ng build --prod
Run Code Online (Sandbox Code Playgroud)

生成 dist 并使用

http-server ./dist/YOUR_DIST_FOLDER_NAME -p 9999
Run Code Online (Sandbox Code Playgroud)

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

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');
});
Run Code Online (Sandbox Code Playgroud)

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


dan*_*iel 4

为了让 service-worker 工作,你需要使用 --prod 进行编译。尝试使用 ng build --prod 进行编译