离子在前景或背景中检测视图 ionViewDidEnter,ionViewWillLeave不被调用

问题描述

我正在尝试检测离子页面是在前台还是在后台

当警报位于视图顶部或模式打开并覆盖父视图时,我想执行一些代码。以及检测何时将它们消散并将视图放回顶部。

ionViewDidEnter和ionViewWillLeave都不会被调用,是否有一种优雅的方法可以不对每个单独的弹出窗口和模式进行处理?

  ionViewDidEnter(){
    debugger;
    //code here
  }
  
  ionViewWillLeave(){
    debugger;
    //code here
  }

解决方法

ionViewDidEnter()和ionViewWillLeave()事件是页面生命周期事件,因此无意在应用程序在前景和背景之间移动时触发。

Cordova提供事件暂停和恢复,分别在应用程序移入后台和前景时触发。实施此操作的一种好方法是使用Ionic's Platform API在app.component文件中注册事件。

您可以导入Platform,在构造函数中提供别名,然后以这种方式注册事件:

import { Platform } from 'ionic-angular';

constructor(public plt: Platform)

this.plt.pause().then(() => {});