Я разрабатываю приложение Angular, которое должно получить уведомление Pu sh от сервера (Laravel с Webpu sh) и затем отобразить его в качестве уведомления. Для этого я использую Angular Service Worker.
В настоящее время я могу протестировать уведомление Pu sh с вкладкой отладки приложения chrome, и уведомление отображается так, как должно. Однако, когда я пытаюсь получить уведомление от сервера, приложение получает его, но ничего не показывает. В качестве обходного пути я создал уведомление непосредственно через API уведомлений браузера, и оно показывает. Однако, это не работает, когда приложение не открыто.
В настоящее время это мой TS в моей службе Pu sh.
import { Injectable } from "@angular/core";
import { RestService } from "./rest.service";
import { AuthService } from "./auth.service";
import { SwPush } from '@angular/service-worker';
@Injectable({
providedIn: "root"
})
export class PushService {
readonly VAPID_PUBLIC_KEY = VAPID_KEY
constructor(
private restservice: RestService,
private authservice: AuthService,
private swPush:SwPush
) {
if (navigator.serviceWorker) {
this.initNotifications();
/*This is the part where i test the message reception from the server, in order to make it work i
use the Browser Notification API and it shows as it should. However, it doesn't fire the
notification if i dont use the "New Notification" and with this approach, the service worker won't
work*/
this.swPush.messages.subscribe((message:any)=>{
var notification = new Notification(message.title,{
body:message.body
})
})
}
}
initNotifications() {
this.swPush.requestSubscription({
serverPublicKey: this.VAPID_PUBLIC_KEY
}).then(sub => this.storePushSubscription(sub))
}
storePushSubscription(pushSubscription) {
let subscriptionData:any = (JSON.parse(JSON.stringify(pushSubscription)));
subscriptionData.user_id = this.authservice.loggedUser.user_id;
console.log(subscriptionData);
this.restservice.post(subscriptionData, "push")
}
}
И это код в Laravel, который отправляет уведомление в методе ToWebPu sh;
класс Pu sh расширяет Уведомление {использовать Queueable;
protected $notificactionObject;
public function __construct($notificactionObject) {
$this->notificactionObject = $notificactionObject;
}
public function via($notifiable)
{
return [WebPushChannel::class];
}
public function toWebPush($notifiable, $notification)
{
return (new WebPushMessage)
->title($this->notificactionObject->title)
->body("Body Text");
}
}