【问题标题】:Ionic open page or tab from component and run function离子从组件打开页面或选项卡并运行功能
【发布时间】:2018-10-20 08:54:08
【问题描述】:

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

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

例如:

  • 用户收到通知,他有一个新的友谊邀请。
  • 用户按下推送通知
  • 应用程序将打开“好友列表”选项卡并打开特定邀请。

【问题讨论】:

    标签: javascript angular typescript cordova ionic-framework


    【解决方案1】:

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

    首先你需要将以下组件添加到你的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
    });
    

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

    【讨论】:

    • 我正在使用但未重定向到第三个选项卡...它仅重定向到第一个根或活动选项卡。 this.app.getRootNav().getActiveChildNav().select(3);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2016-02-14
    相关资源
    最近更新 更多