1. 程式人生 > >ionic v4 關於返回鍵監聽 (hardware back button)

ionic v4 關於返回鍵監聽 (hardware back button)

android手機上的返回鍵,會自動的使路由後退。但少數時候我們可能不需要這個後退功能,希望自己監聽點選回退操作。

比如,想通過點選返回按鈕關閉一個modal,並且不想後退。

1.使用@HostListener 監聽ionBackButton事件

@HostListener('document:ionBackButton', ['$event'])
private overrideHardwareBackAction($event: any) {
  $event.detail.register(100, async () => {
  // Do what you want
  this.modalController.dismiss();  }); }

注意這個 $event.detail.register

2.使用 subscribeWithPriority 訂閱 platform.backButton

 private handleHardwareBackButton(): void {
    const sub = this.platform.backButton.subscribeWithPriority(9999, () => {
      console.log('called');
      this
.dismiss(); }); this.subscriptions.push(sub); } ngOnInit() { this.getStates(this.payload); this.handleHardwareBackButton(); } ngOnDestroy() { unsubscribeSubscriptions(this.subscriptions); }

這個方法同樣是有效的,不過我不知道使用多少優先順序是最合適的,這方面的文件是在太少。

上面兩個方法都是我在github上找到的,希望幫助到使用ionic 4和我有同樣問題的人。