ionic3 + angular4 在 android手机上物理键返回问题

问题描述:

  最接近公司为某行开发的项目遇到了这么一个问题:某行从自己开发的应用跳转到我们开发的应用之后,经过一系列操作之后不管当前页面处于哪一个页面,点击android手机物理键返回的时候都会直接返回到我们应用的第一个页面。

问题分析:

  咨询某行本部开发人员之后了解到,从他们的应用跳转到我们的应用是通过链接地址的形式。也就是说我们的应用相当于在浏览器上运行的,而不是我们平时开发那样打包安装到手机上运行的。由此想到 angular4 开发的其实是一个单页应用,因此返回就不会按路由队列顺序依次返回。

问题解决:

  想办法添加window.history记录,并在页面回到首页的时候使 页面 history 回到应用刚打开时的 history 队列位置;history返回的时候要当前页面路由队列也要返回。结合 history Api 、 NavController 、 ionci3 生命周期得出解决方案如下:

  1、定义超类 BasePage,并在构造函数中通过TS代码添加history记录;

  2、所有的Page页面都继承超类BasePage;

  3、首页添加首页标识 ifIndex:boolean = false, 并在 ionViewDidEnter 生命周期 中设置为true;

  4、首页 构造函数中绑定window.onpopstate()事件,判断当当前路由队列可以返回的时候当前路由执行pop方法,当当前页面是首页并且event.state !== null 的时候window.history.back();

BasePage:


import {NavController, NavParams} from 'ionic-angular'; export class BasePage { constructor(public navCtrl: NavController, public navParams: NavParams) { // 添加浏览器访问记录 window.history.pushState(this.constructor.name, '', ''); } }

HomePage:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {BasePage} from "../BasePage";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage extends BasePage{

  /**
   * 变量,判断当前页面是否是首页
   * @type {boolean}
   */
  ifIndex: boolean = false;

  constructor(public navCtrl: NavController){
    super(navCtrl,null); // 初始化父类
    let that = this;
    // window绑定onpopstate事件,用于处理浏览器返回事件
    window.onpopstate = function(event){
      // 如果当前路由存在前一个页面  返回前一个页面
      if(that.navCtrl.canGoBack()){
        that.navCtrl.pop();
      }
      // 如果当前页面是第一个页面,并且event.state !== null 返回前一个页面
      if(that.ifIndex === true && event.state !== null){
        window.history.back();
      }
    }
  }

  ionViewDidEnter(){
    // 页面激活后更新 enableAutoBack 为true,
    this.ifIndex = true;
    // 因为超类中添加了一条history记录 此处返回前一页来触发window.onpopstate事件
    window.history.back();
  }

  ionViewWillLeave(){
    // 从当前页面离开 enableAutoBack 为 false
    this.ifIndex = false;
  }
}