我无法处理Ionic 4上的android后退按钮

时间:2019-09-24 01:40:14

标签: angular typescript ionic-framework ionic4 ionic-native

我是离子发展方面的新手。通过关注文章,我尝试了越来越多的方法。 最后,我尝试了这个Handling hardware back button in Ionic3 Vs Ionic4 请帮助我 @Fabian N.

但是在设备上,后退按钮的工作是否与代码无关,这在我的情况下是行不通的。 :(

这是我的离子信息。

Ionic:

   Ionic CLI                     : 5.2.3 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.6.2
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.3.9
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.5.1

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : android 8.0.0, ios 5.0.1
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 4.1.1, (and 16 other plugins)

Utility:

   cordova-res : not installed
   native-run  : 0.2.8 

System:

   ios-deploy : 1.9.4
   ios-sim    : 8.0.1
   NodeJS     : v11.10.1 (/usr/local/bin/node)
   npm        : 6.7.0
   OS         : macOS Mojave
   Xcode      : Xcode 10.2 Build version 10E125

我已经在app.component.ts中尝试了波纹管事件。但单击“后退”按钮时,我无法在真实设备上收到任何警报。

1. Test case
  this.platform.backButton.subscribe(async () => {
     alert("Fired Back Button"); 
  });

2. Test case
  this.platform.backButton.subscribe(() => {
     alert("Fired Back Button"); 
  });

3. test case
  this.platform.backButton.subscribeWithPriority(0, () => {
     alert("Fired Back Button"); 
  });



4. test case
  this.platform.backButton.subscribeWithPriority(100, () => {
     alert("Fired Back Button"); 
  });

在这种情况下,我尝试了优先级:100、101、400、999999。但是单击android后退按钮时我不会收到任何警报。

但是实际上后退按钮总是会弹出页面。

我只需要处理项目上的android硬件后退按钮。 请帮我。 先感谢您。 最好的问候

3 个答案:

答案 0 :(得分:1)

最后,我对我的问题有正确的答案。 解决方案是Enol's answer。我已经在app.component.ts文件中写过。

const event = fromEvent(document, 'backbutton');
event.subscribe(async () => {
  // logic for navigation, modal, popover, menu closing
  this.navCtrl.pop(); // I have used for my case

  ...

});

感谢Markus

答案 1 :(得分:1)

重构智艺的答案

这项工作!

    const event = fromEvent(document, 'ionBackButton');
    event.subscribe(async () => {
        console.log('hardware back button triggered')
    })

    //you may want store that subscription and unbscribe on ngOnDestroy.

peterpeterparker solution from github

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

答案 2 :(得分:-1)

您可以尝试这个

this.platform.backButton.subscribe(() => {
  // this does work
});