首页 > 解决方案 > 离子从组件打开页面或选项卡并运行功能

问题描述

我正在努力解决以下问题。在我的 Ionic (3) 应用程序中。我在 app.component.ts 文件中获得了 oneSignal(推送通知)处理脚本。当用户按下推送通知时,我使用该handleNotificationOpened().subcribe功能能够打开页面或运行功能。

现在我的问题是,如何从 app.component.ts 更改选项卡或页面并在打开该选项卡/页面时运行特定于页面的功能。

例如:

标签: javascriptangulartypescriptcordovaionic-framework

解决方案


对于有同样问题的人,我使用事件找到了解决方案。它可能不是最好的解决方案,但它确实有效。

首先,您需要将以下组件添加到您的 page.ts

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

当用户使用 OneSignal 按下推送通知时,会触发以下函数。

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);

});

以下功能将用户引导到右侧选项卡

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');    
} 

以及将数据提交到其他页面的功能:

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);
}

最后,我们必须在您要重定向到的其他选项卡/页面上添加一个事件侦听器。

// 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
});

如果有人有任何问题,请随时提问!


推荐阅读