Ionic open page or tab from component and run function (on notification press)


#1

I’'m struggling with the following issue. In my Ionic (3) application. I got the oneSignal (push notifications) handling script in my app.component.ts file. I’m using the handleNotificationOpened().subcribe function to be able to open a page or run a function when a user presses the push notification.

Now my question is, how can I change tab or page from app.component.ts and run a page specific function while opening that tab/page.

For instance:

  1. User get notification that he has a new friendship invite.
  2. User presses the push notification
  3. App will open “friendlist” tab and opens the specific invite.

Hope somebody is able to help, couldn’t get this sorted out.


#2

For people having the same question, I found the solution using events. It may not be the best solution but it works.

First you need to add the following components to your page.ts

import { Events } from 'ionic-angular';
import { App } from 'ionic-angular';

The following function fires when the user press the pushnotification.

this.oneSignal.handleNotificationOpened().subscribe((data) => {
    // do something when a notification is opened

    // the following two lines pass data I send with the push notification so the app knows what to open
    let pushaction = data.notification.payload.additionalData.action;
    let pushactionvalue = data.notification.payload.additionalData.actionvalue;

    // this fires up the tab-switching
    this.runNotificationAction(pushaction, pushactionvalue);
			  
});

The following function directs user to the right tab

runNotificationAction(pushaction, pushactionvalue){

    // this is the data passed the the other page
    let data = {"action": pushaction, "value:": pushactionvalue};

    // this opens the right tab. Make sure to change select '0' to the required tab (0 is the first one). 
    this.app.getRootNav().getActiveChildNav().select(0);

    // fires the function that passed the data. Using second parameter to filter event listeners per page. 
    this.sendData(data, 'homepage');	
} 

And the function that submits the data to the other pages:

sendData(data, command){
    //We set a timeout because I had problems with sending it imediatly. Like this it works fine for me.
    setTimeout(() => {
        let pushcommand = "pushData:" + command ;
        this.events.publish(pushcommand, data);
    }, 500);
}

And at last we have to add an event listener on the other tabs/pages you are going to redirect to.

// making an event listerner command for each page like pushData:homepage makes sure the action is only fired from the specific page
this.events.subscribe('pushData:homepage', (data) => {
    console.log('Yes, data passed!');
    console.log(data);
   // Then you can fire your function and use the data
});

If anyone has any questions feel free to ask!