2017-07-06 49 views
1

我想攔截後退按鈕事件。 一旦收聽者被呼叫,後面的信號就已經被觸發。離子3塊後臺事件

這是我的嘗試:

document.addEventListener("backbutton",() => { 
     console.log("[WARN] BackBtn pushed"); 
     console.log("TextboxVal: " + this.inputValue); 
     this.showConfirm(); 
     document.removeEventListener("backbutton"); 
    }); 

我不想失去 「this.inputValue」 值。 但在大多數情況下,它已經消失了。

+0

你可能想要考慮cookies https://www.npmjs.com/package/cookies-js和Reactive Forms。 https://angular.io/guide/reactive-forms這樣,如果你離開並返回狀態可以保存。 Angular大學的Vasco在他的RxJS教程視頻中對此做了些什麼。請參閱https://angular-university.io/lesson/angular-rxjs-reactive-patterns-reactive-forms-draft-data-saving-implementation實際上,它使用form.valueChanges,並在表單處於使用過濾器的有效狀態 – JGFMK

+0

有幾種方法可以解決這個問題,但我不確定您的目標有哪些要求。您可以a)將值存儲在存儲器中,所以當用戶返回頁面時,值會在那裏b)在離開頁面之前顯示警報,如果用戶仍然想離開,清除該輸入並返回到上一頁。如果這可能有效,請告訴我,我會添加更多詳細信息的答案。 – sebaferreras

+1

我想在離開頁面之前顯示警報。 – MrFlyingToasterman

回答

0

我想在離開頁面之前顯示警報。

您可以使用NavGuards爲:

在某些情況下,開發者應該能夠控制的觀點離開, 進入。爲了做到這一點,NavControllerionViewCanEnterionViewCanLeave方法。類似於角路線衛士,但 更與NavController合併。

// ... 

    ionViewCanLeave() { 

    if(this.inputValue) { 
     // Show the alert 
     this.presentConfirm(); 
    } 

    // Will leave if the input is null 
    return this.inputValue === null; 
    } 

    presentConfirm() { 
    let alert = this.alertCtrl.create({ 
     title: 'Exit', 
     message: 'Do you want to exit?', 
     buttons: [ 
     { 
      text: 'Cancel', 
      role: 'cancel' 
     }, 
     { 
      text: 'Exit', 
      handler:() => { 

      // Allow the user to exit this page 
      this.inputValue = null; 

      // Go back to the previous page 
      setTimeout(() => { this.navCtrl.pop(); }, 500); 

      } 
     } 
     ] 
    }); 
    alert.present(); 
    } 
0

這就是我如何通過自己做了:

constructor(public plt: Platform) { 
    //Catch BackBTN Event 
     plt.ready().then(()=> { 
      plt.registerBackButtonAction(()=> { 
      this.showConfirm(); 
      }) 
     });​ 
} 

showConfirm() { 
     let confirm = this.alertCtrl.create({ 
     title: this.confirm, 
     message: this.confirm_msg, 
     buttons: [ 
      { 
      text: this.disagree, 
      handler:() => { 
       console.log("Saved changes"); 
       this.dismiss(); 
      } 
      }, 
      { 
      text: this.agree, 
      handler:() => { 
       console.log("Discard changes"); 
       this.viewCtrl.dismiss(); 
      } 
      } 
     ] 
     }); 
     confirm.present(); 
    } 
    } 

有了這個,我可以把我自己的自定義BackBTN方法。

+0

該方法的問題是,將爲所有頁面設置該行爲,而不僅僅在該頁面中設置該行爲。您可以嘗試取消註冊自定義後退按鈕處理程序,但有時會導致應用程序中出現一些錯誤,當多個頁面從堆棧中彈出/彈出時。 – sebaferreras