我正在尝试使用Ionic推送通知。这是我当前的app.component.ts:
import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import {
Push,
PushToken
} from '@ionic/cloud-angular';
import { Page1 } from '../pages/page1/page1';
import { Page2 } from '../pages/page2/page2';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
rootPage: any = Page1;
pages: Array<{title: string, component: any}>;
constructor(
public platform: Platform,
public push: Push
) {
this.setupPushNotifications();
this.initializeApp();
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Page One', component: Page1 },
{ title: 'Page Two', component: Page2 }
];
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
});
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
setupPushNotifications() {
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
this.push.rx.notification()
.subscribe((msg) => {
console.log(msg);
alert(msg.title + ': ' + msg.text);
});
}
}
然后我使用以下Node.js应用程序发送推送消息:
var request = require('request');
function sendMessageToUser(deviceId, message) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key=AI....'
},
body: JSON.stringify(
{
"to" : deviceId,
"notification": {
"title": "Push Notification",
"body": message,
"sound": ""
},
"data": {
"test": "test 1"
}
}
)
}, function(error, response, body) {
if (error) {
console.error(error, response, body);
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body);
}
else {
console.log('Done!')
}
});
}
sendMessageToUser(
"eu....",
'Test'
);
如果应用程序已打开且我发送推送通知,则console.log()
和alert()
执行确定。但是,当应用程序在后台或手机被锁定时,我会按预期收到通知,但是当我点击此按钮时,应用程序会打开而不执行console.log()
或alert()
功能。< / p>
有人可以告诉我如何实现这个目标吗?
我尝试过从Ionic.io的云系统发送推送通知,并且在使用它时工作正常,所以我的节点应用程序中可能缺少一个选项?
感谢您的帮助。