【问题标题】:Ionic-5 app is closing instead back to previous page on click of hardware back buttonIonic-5 应用程序正在关闭而不是单击硬件后退按钮返回上一页
【发布时间】:2020-09-14 02:28:09
【问题描述】:

我正在使用 angular 7ionic 5。当我想使用硬件后退按钮重定向到上一页时,离子应用程序正在自行关闭。我正在使用下面的代码,但它不起作用。

 this.platform.backButton.subscribeWithPriority(9999, () => {
        document.addEventListener('backbutton', function (event) {
          event.preventDefault();
          event.stopPropagation();
          console.log('hello');
        }, false);
      });

【问题讨论】:

    标签: android ionic5


    【解决方案1】:

    如果您将 ionicCapacitor 一起使用,则需要在 app.component.ts 的构造函数中使用此代码:

    import { App } from '@capacitor/app';
    import { Location } from '@angular/common';
    
    constructor(private _location: Location)
    {
      App.addListener('backButton', () =>
      {
        if (this._location.isCurrentPathEqualTo('/home'))
        {
          navigator['app'].exitApp();
        } 
        else
        {
          this._location.back();
        }
      });
    }
    

    【讨论】:

      【解决方案2】:

      我为此使用指令

      import { Directive, HostListener } from '@angular/core';
      import { PlatformService } from 'src/app/services/platform';
      
      @Directive({
          selector: '[disableBackButton]'
      })
      export class DisableBackButtonDirective {
      
          constructor(
              private platformService: PlatformService
          ) { }
      
          @HostListener('document:ionBackButton', ['$event'])
          overrideHardwareBackAction(event: any) {
              if (this.platformService.isPlatform('android')) {
                  event.detail.register(100, async () => {
                      event.stopImmediatePropagation();
                      event.stopPropagation();
                      event.preventDefault();
                  });
              }
          }
      }
      

      在page.html中

      <ion-content disableBackButton>
          ....
      </ion-content>
      

      在page.ts中

      this.platform.backButton.subscribe(() => {
          console.log('hello');
      });
      

      【讨论】:

        【解决方案3】:

        试试这个,

         this.platform.backButton.subscribeWithPriority(10, () => {
              this.router.navigate(['']); // route to previous page or component
         });
        

        【讨论】:

          猜你喜欢
          • 2021-10-15
          • 1970-01-01
          • 2023-03-19
          • 2015-12-24
          • 2020-01-14
          • 2020-01-12
          • 2015-10-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多