Ionic 3 FCM open specific pages when notification tapped when app is in background/closed

I can get the push notification when my apps is on background/closed and I can get the data in the payload of the notifications when i tapped it and open

"notification": {
    "title": "Chat Messages",
    "body": `You have received chat messages from ${userName}`,
    "sound": "default",
    "click_action":"FCM_PLUGIN_ACTIVITY",
    "icon":"fcm_push_icon"
},
"data": {
    "user_id" : from_user_id,
    "user_name" : userName,
    "type" : notification_type
}

but there is a problem which I can't make it open a specific page after i tapped the notification when in background/closed.

Here is my code in the app.components.ts:

import { Component, ViewChild } from '@angular/core';
import { Platform, NavController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { FCM } from '@ionic-native/fcm';

import { LoginPage } from '../pages/login/login';
import { TestpagePage } from '../pages/testpage/testpage';

@Component({
   templateUrl: 'app.html'
})
export class MyApp {
@ViewChild('myNav') navCtrl: NavController
rootPage:any = LoginPage;

constructor(fcm: FCM, platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
   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();

  fcm.onNotification().subscribe(function(data) {
    if(data.wasTapped) {
      alert('HI');
      if(data.type == 'messages') {
        alert('HEY');
        this.navCtrl.setRoot(TestpagePage);
      }

    } else {
      alert('Untapped<br>' +
            'User ID: ' + data.user_id + 
            '<br>User Name: ' + data.user_name +
            '<br>Type: ' + data.type);
     }
   });
  });
 }
}

It will execute the 'HI' and 'HEY' alert inside the if(data.wasTapped) { but it seems like the this.navCtrl.setRoot('TestpagePage'); is not fired. I don't know why please help me!

1 answer

  • answered 2018-04-17 04:13 kelvin wong

    So the problem have been solved.

    Like @SurajRao suggested, instead of using fcm.onNotification().subscribe(function(data) { I followed his suggestion and updated my code to fcm.onNotification().subscribe((data) => { and it works.