Я пытаюсь заставить push-уведомления работать в Angular 7, используя ссылку и с помощью SwPush. Я не могу получать push-уведомления. В настоящее время я работаю на localhost (запустив http-сервер после выполнения ng-build), а мой сервер api находится в облаке. Мне удалось включить подписку с помощью swPush.requestSubscription, и подписка успешно зарегистрирована на сервере. В Chrome все вызовы api блокируются самим сервисным воркером (сбой: сервисным воркером), в то время как в Firefox ошибки нет, но push-сообщение не появляется.
Ниже я добавил соответствующие фрагменты кода. Поскольку сообщений о конкретных ошибках не поступало, я не могу продолжить.
Посоветуйте, пожалуйста, как заставить это работать и показывать уведомления.
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')
}
}
}));
}
}