单击硬件后退按钮,Ionic-5应用程序将返回上一页



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

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

如果您将ionic电容器一起使用,则需要在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();
}
});
}

我使用这个的指令

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>

第.ts页

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

试试这个,

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

最新更新