2017-07-06 50 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