【问题标题】:To close the app from particular page on single tap of hardware back button单击硬件后退按钮从特定页面关闭应用程序
【发布时间】:2020-01-14 01:10:15
【问题描述】:

我的应用由两个页面组成,分别称为loginhome 和其他延迟加载的modules。 在app.component.ts 中,写入条件使得如果localStorage 为空,它应该路由到login 页面,否则它应该路由到home 页面。然后从主页用户将路由其他延迟加载的模块

app.component.ts

    import { Component } from '@angular/core';
    import { SplashScreen } from '@ionic-native/splash-screen/ngx';
    import { StatusBar } from '@ionic-native/status-bar/ngx';
    import { Platform, NavController } from '@ionic/angular';

    @Component({
      selector: 'app-root',
      templateUrl: 'app.component.html'
    })
    export class AppComponent {

      constructor(
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        private platform: Platform,
        public navCtrl: NavController,
      ) {
        this.initializeApp();
        if (localStorage.getItem('token') !== null) {
          this.navCtrl.navigateRoot('/home');
        } else {
          this.navCtrl.navigateRoot('/login');
        }
      }

        initializeApp() {
          this.platform.ready().then(() => {
            this.statusBar.styleDefault();
            this.splashScreen.hide();
            this.platform.ready().then(() => {
            });
        });
      }


    }

app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

    const routes: Routes = [

      {path: 'home',loadChildren: './home/home.module#HomePageModule'},
      { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
      { path: '', loadChildren: './nav-bar/nav-bar.module#NavBarPageModule' },  <===== Lazy loaded module
      { path: '', loadChildren: './nav-bar-provider/nav-bar-provider.module#NavBarProviderPageModule' }, <===== Lazy loaded module
    ];

    @NgModule({
      imports: [
        RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
      ],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

这种情况可以正常工作。然后在home 页面中,我编写了代码以在 双击 时退出应用程序,如下所示:

home.page.ts

    import { Component , OnInit} from '@angular/core';
    import { Platform } from '@ionic/angular';
    @Component({
      selector: 'app-home',
      templateUrl: 'home.page.html',
      styleUrls: ['home.page.scss'],
    })
    export class HomePage implements OnInit {
      subscription;
      constructor(public platform: Platform) {}

      ngOnInit() {}

      ionViewDidEnter() {
        this.subscription = this.platform.backButton.subscribe(() => {
          (navigator as any).app.exitApp();
        });
      }
      ionViewDidLeave() {
        this.subscription.unsubscribe();
      }
    }

现在的问题是:On double tap in home page,the app will close, But on single tap it will routed 1st lazy loaded module(i,e NavBarPageModule). How can avoid this? 对于这个问题,我尝试将 router-path 提供给延迟加载的模块,如下所示:

    const routes: Routes = [

      {path: 'home',loadChildren: './home/home.module#HomePageModule'},
      { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
      { path: 'nav-bar', loadChildren: './nav-bar/nav-bar.module#NavBarPageModule' }, 
      { path: 'nav-bar-provider', loadChildren: './nav-bar-provider/nav-bar-provider.module#NavBarProviderPageModule' },
    ];

然后我无法从home 页面路由到lazy loaded modules

我只想通过单击从home page 关闭应用程序。

【问题讨论】:

  • 你能分享一下你是如何实现双击绑定的吗?锤子.js?这可以帮助你;)还有什么是预期的最终状态 - 如果在主页上单击应该会发生什么?
  • 在主页上单击后退按钮,应用程序应关闭。
  • 你能分享一下登录方法吗?比如点击登录功能。之后,我会为您提供任何解决方案。
  • 在登录页面,点击按钮called,我会调用这个方法public onLogin() { this.navCtrl.navigateRoot('/home'); } 然后用户将被路由到home 页面。
  • 你试过用 ionViewWillLeave 代替 ionViewDidLeave 吗?

标签: angular typescript ionic-framework


【解决方案1】:

我正在发布对我有用的solution,它可能对其他用户有所帮助。

app.component.ts 文件应如下所示:

import { Component } from '@angular/core';
import { Platform, ToastController } from '@ionic/angular';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  counter = 0;

  constructor(
              public platform: Platform,
              public toastController: ToastController
  ) { 
    this.platform.ready().then(() => {
      document.addEventListener('backbutton', async () => {
          if (this.counter === 0) {
            this.counter++;
            this.alertToast();
            setTimeout(() => { this.counter = 0; }, 3000);
          } else {
            (navigator as any).app.exitApp();
          }
      });
    });
  }

  async alertToast() {
    const toast = await this.toastController.create({
      message: 'Press again to exit',
      duration: 300,
      position: 'middle',
    });
    toast.present();
  }


}

【讨论】:

    【解决方案2】:

    试试这个:

    document.addEventListener('backbutton', function(event){
      event.preventDefault();
      navigator.app.exitApp(); // exit the app
    });
    

    希望对你有所帮助。

    【讨论】:

      【解决方案3】:

      试试这个使用 Ionic 4 和浏览器 API 的 sn-p:

      if (this.platform.is("android")) {
          this.platform.backButton.subscribe(() => {
              if (window.location.pathname === "/home") {
                  navigator['app'].exitApp();
              }
          });
      }
      

      【讨论】:

        【解决方案4】:

        1)在你的组件中导入 IonRouterOutlet

        import { IonRouterOutlet } from '@ionic/angular';
        

        2) 添加 Viewchildren

          @ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;
        

        3)最后在你的组件中编写代码

        this.platform.backButton.subscribe(async () => {

        this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
          if (this.router.url.match('/home')) {
                    navigator['app'].exitApp(); // work for ionic 4
          };
        

        }) });

        【讨论】:

        • 抱歉回复晚了,我也试过这个解决方案。还是同样的问题。
        猜你喜欢
        • 2018-04-04
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多