【问题标题】:Displaying push notifications in angular以角度显示推送通知
【发布时间】:2019-10-29 02:24:10
【问题描述】:

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

推送通知.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:domain@test.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: {
      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');
});
  • 使用上面的代码,我正在尝试使用 angular 和 express 显示通知。我在http://localhost:3000 上启动了服务器,然后运行ng build --prod then http-server dist/apps/projectName

  • 无论是否允许,通知请求都有效,单击允许时,我收到响应 200(检查网络选项卡 Chrome 开发工具)。但是通知消息没有弹出或显示在浏览器中。我需要帮助来解决这个问题。

我尝试了https://malcoded.com/posts/angular-push-notifications/的代码

谢谢。

【问题讨论】:

    标签: angular angular7 web-push


    【解决方案1】:

    您好像忘记添加弹出消息了:

    pushService.sendSubscriptionToTheServer(subscription).subscribe(change => {
    
        //-->Here you need to write popup message after notification
    
    })
    

    【讨论】:

    • 谢谢,有什么语法吗?
    • 因此没有语法,但您可以使用警报或自定义方式显示消息框。
    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多