【发布时间】:2019-05-17 12:33:17
【问题描述】:
我正在尝试使用 @angular/pwa link 和 SwPush 使推送通知在 Angular 7 中工作。我无法获得实际的推送通知。 我目前正在本地主机上工作(通过在执行 ng-build 后运行 http-server)并且我的 api 服务器位于云中。 我能够使用 swPush.requestSubscription 启用订阅,并且订阅已在服务器上成功注册。 在 Chrome 中,所有 api 调用都被 service Worker 本身阻止(失败:来自 service Worker),而在 Firefox 中,没有错误但没有出现推送消息。
我已经在下面添加了相关代码sn-ps。由于没有报告具体错误,我无法继续进行。
请告知如何进行这项工作并显示通知。
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')
}
}
}));
}
}
【问题讨论】:
-
你有 https 吗? PWA 不适用于开发版本。
-
你能用 stackblitz(stackblitz.com) 重现错误吗?
-
@DharanG 我正在本地环境中测试它,而不是在开发环境中。
标签: angular push-notification progressive-web-apps angular-service-worker