gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:26:26 25 4
gpt4 key购买 nike

我正在尝试使用@angular/pwa 使推送通知在 Angular 7 中工作 link并使用 SwPush。我无法获得实际的推送通知。我目前正在本地主机上工作(通过在执行 ng-build 之后运行 http-server)并且我的 api 服务器位于云中。我能够使用 swPush.requestSubscription 启用订阅,并且订阅已在服务器上成功注册。在 Chrome 中,所有 api 调用都被 service worker 本身阻止(失败:来自 service worker),而在 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
}
}

推送通知服务

 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')
}
}
}));
}
}

最佳答案

您需要安装 Angular CLI、Service Worker 的 PWA、生成 VAPID key 的 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 key 对,以便在前端和后端使用

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 是你之前得到的公钥。

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

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');
});

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

关于Angular 7 pwa/SwPush - 推送通知不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53810194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com