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

问题描述:
  最接近公司为某行开发的项目遇到了这么一个问题:某行从本身开发的应用跳转到咱们开发的应用以后,通过一系列操做以后无论当前页面处于哪个页面,点击android手机物理键返回的时候都会直接返回到咱们应用的第一个页面。html

问题分析:
  咨询某行本部开发人员以后了解到,从他们的应用跳转到咱们的应用是经过连接地址的形式。也就是说咱们的应用至关于在浏览器上运行的,而不是咱们平时开发那样打包安装到手机上运行的。由此想到 angular4 开发的实际上是一个单页应用,所以返回就不会按路由队列顺序依次返回。android

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

  一、定义超类 BasePage,并在构造函数中经过TS代码添加history记录;
  二、全部的Page页面都继承超类BasePage;
  三、首页添加首页标识 ifIndex:boolean = false, 并在 ionViewDidEnter 生命周期 中设置为true;
  四、首页 构造函数中绑定window.onpopstate()事件,判断当当前路由队列能够返回的时候当前路由执行pop方法,当当前页面是首页而且event.state !== null 的时候window.history.back();angular4

BasePage:ionic


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;
  }
}
相关文章
相关标签/搜索