2

当我在 android 上构建并运行我的应用程序时,我意识到硬件后退按钮不起作用。我有主页,它有两个孩子,一个主页和一个收藏页面,主页是默认页面。如果我在收藏夹页面并单击后退按钮,它会将我带到主页,但从主页上,如果我单击后退按钮,它会显示白屏并在几秒钟后重新启动应用程序。如果我单击它三下,我将只能关闭该应用程序。我正在使用离子 4,Angular 8。

这是我的应用程序路线的样子:

  { path: '', loadChildren: './pages/main/main.module#MainPageModule' },
  { path: 'search', loadChildren: 
  './pages/search/search.module#SearchPageModule' },
  { path: 'catalog-view', loadChildren: './pages/cat-view/cat- 
  view.module#CatViewPageModule' },

这是我的主要模块的样子:

const routes: Routes = [
  {
    path: 'main',
    component: MainPage,
    children: [
     { path: 'home', loadChildren: '../home/home.module#HomePageModule' },
      { path: 'favorites', loadChildren: 
     '../favorites/favorites.module#FavoritesPageModule' },
       ]
      },
      {
        path: '',
       redirectTo: '/main/home'
       }
   ];

我尝试在主页上添加此功能,然后是 Main,甚至 Appcomponent,但没有任何效果:

ionViewDidEnter(){
  this.subscription = this.platform.backButton.subscribe(()=>{
      navigator['app'].exitApp();
  });
}

 ionViewWillLeave(){
  this.subscription.unsubscribe();
 }
4

2 回答 2

2

我得到了它的工作,这个问题非常愚蠢。我不得不将我的包更新到最新版本,尤其是@ionic-native/core。在我的 home.ts 中,我只是这样做:

ngOnInit(){
     this.platform.backButton.subscribe(() => {
     this.platform.backButton.unsubscribe();
     navigator['app'].exitApp();
   })
)

希望能帮助到你!

于 2019-08-16T09:44:24.077 回答
1

我的主页中有以下代码,他在主页上向后退按钮注册了不同的功能。然后在它离开后立即再次注销它。

private isToastShown: boolean = false;

ionViewDidEnter(){
        /* When on home page the back button should confirm before exiting */
        this.platform.backButton.subscribeWithPriority(0, () => {
            if (!this.isToastShown) {
                this.presentConfirm();
            } else {
                navigator['app'].exitApp();
            }
        }, 0);
    }

    ionViewWillLeave() {
        /* Reset back button to pop pages when pressed */
        this.aPlatform.registerBackButtonAction(() => {
            if (this.aNavController.canGoBack()) {
                this.aNavController.pop();
            }
        });
    }

    private presentConfirm(): void {
        this.isToastShown = true;

        let lToast = this.aToastController.create({
            message: "Press back again to exit"
        });

        lToast.present().then(() => {
            setTimeout(() => {
                lToast.dismiss();
                this.isToastShown = false;
            }, 2000);
        });
    }

希望这可以帮助

于 2019-08-16T06:18:34.150 回答