App.ts
const VAPID_PUBLIC = "XXX"
export class AppComponent {
title = 'web';
constructor(swPush: SwPush, pushService: PushNotificationService) {
if (swPush.isEnabled) {
swPush
.requestSubscription({
serverPublicKey: VAPID_PUBLIC,
})
.then(subscription => {
pushService.sendSubscriptionToTheServer(subscription).subscribe(change => {
})
})
.catch(console.error)
}
}
push-notification.service.ts
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
const SERVER_URL = 'http://localhost:3000/subscription'
@Injectable()
export class PushNotificationService {
constructor(private http: HttpClient) {}
public sendSubscriptionToTheServer(subscription: PushSubscription) {
return this.http.post(SERVER_URL, subscription)
}
}
server.js
const express = require('express');
const webpush = require('web-push');
const cors = require('cors');
const bodyParser = require('body-parser');
const PUBLIC_VAPID =
'XXX';
const PRIVATE_VAPID = 'XXX';
const fakeDatabase = [];
const app = express();
app.use(cors());
app.use(bodyParser.json());
webpush.setVapidDetails('mailto:[email protected]', PUBLIC_VAPID, PRIVATE_VAPID);
app.post('/subscription', (req, res) => {
const subscription = req.body;
fakeDatabase.push(subscription);
});
app.post('/sendNotification', (req, res) => {
const notificationPayload = {
notification: {
title: 'New Notification',
body: 'This is the body of the notification',
},
};
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');
});
With the above code, I'm trying to display notifications using angular and express. I started the server on
http://localhost:3000then ranng build --prodthen http-server dist/apps/projectName.The request for notifications is working whether to allow or not, on clicking allow, I get response 200 in (checking in network tab chrome dev tools). But the notification message is not getting popped up or displayed in the browser. I need help in fixing this.
I tried the code from https://malcoded.com/posts/angular-push-notifications/
Thank you.