I am trying to use Ionic push notifications. This is my current 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);
});
}
}
I am then using the following Node.js app to send push messages:
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'
);
If the app is open and I send a push notification, the console.log()
and the alert()
execute OK. However when the app is in the background or the phone is locked, I get a notification as expected, but then when I click on this the app opens without executing either the console.log()
or the alert()
function.
Could someone please tell me how I can achieve this?
I have tried sending push notifications from Ionic.io's cloud system instead, and it works fine when using that so perhaps I am missing an option in my node app?
Thanks for any help.