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;
  }
}
相關文章
相關標籤/搜索