我正在尝试实施推送通知的 Ionic Capacitor 项目。问题是我无法获取设备令牌。我已经按照 Capacitor 网站上提供的文档进行操作,但仍然没有。
我错过了什么?
这是我的服务文件:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Plugins, PushNotification, PushNotificationToken, PushNotificationActionPerformed } from '@capacitor/core';
import { AlertButtons, AlertMessage, AlertTypes } from '../interfaces/helper.interface';
import { HelperService } from './helper.service';
import { SERVER_URL } from '../../../environments/environment';
const { PushNotifications } = Plugins;
@Injectable( { providedIn: 'root' } )
export class PushNotificationsService {
private endPoint = `${SERVER_URL}/device`;
constructor(
private helperService: HelperService,
private httpClient: HttpClient
) {}
public initializeNotificationTasks() {
this.registerDevice();
this.requestPermission();
this.listenToNotifications();
}
private requestPermission() {
console.log('request permission')
PushNotifications.requestPermission()
.then(res => {
console.log(res.granted)
if (res.granted) {
PushNotifications.register();
} else {
this.helperService.displayAlert(AlertTypes.ERROR);
}
})
.catch( (e) => {
const errorMessage = new AlertMessage();
errorMessage.title = 'Error';
errorMessage.message = e;
errorMessage.buttons = [AlertButtons.DISMISS];
this.helperService.displayAlert(AlertTypes.ERROR, errorMessage);
});
}
private registerDevice() {
PushNotifications.addListener( 'registration', ( token: PushNotificationToken ) => {
return this.httpClient.post(this.endPoint, { device_id: token.value });
} );
}
private listenToNotifications() {
PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => {
// Returns as JSON.stringfy(notification)
return notification;
});
}
}