Preventing loging out on pressing back button Ioni

2019-09-07 22:23发布

问题:

Actually I am creating an App in Ionic2 in which I have set my root page as loginpage in which user adds his credentials and on successfull login is redirect to another pages using setRoot say Page1.

The issue is that on pressing back button from app in mobile app closes and user is forced again to login screen but I want its session to be set.

Can any one suggest whats the issue and how I can overcome this.

I have used ionic2 with menus as a kick start.

回答1:

I've come accross this problem before, and my solution was to setup a LoggedIn state in a service that I would call from my guard to my login component, making the redirection to the main part of the app if I was already loggedIn.

Example :

This methods calls my ASP.NET Controller that would get a Session parameter (set beforehand by the login method) to know if the user has been authenticated or not and then sets the corresponding value to my service boolean (this.isLoggedIn).

Auth.service.ts

setupLoggedInState() {
    // HTTP Request to API
    let lControllerAction: string = "/IsConnectedState";
    let lControllerFullURL: string = this.controllerURL + lControllerAction;
    let headers = new Headers({ 'Content-Type': 'application/json' });
    // Empty body (necessary for this specific call)
    let options = new RequestOptions({ headers: headers, body: "" });
    // Call ASP Controller
    return this.http.get(lControllerFullURL, options)
        .map((res: any) => {
            let data = res.json();
            if (data == true) {
                this.isLoggedIn = true;
            }
        }
        ).catch(this.handleError);
}

Here is an example of making it work with my guard. I have as well some specific code to manage whether the user would manually input an URL or not, so you won't need all of that.

Auth.guard.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    // Set IsLoggedIn if user has been authenticated before
    return this.authService.setupLoggedInState()
        .map(loggedIn => {
            // Check result
            if (this.authService.isLoggedIn) {
                // Managing redirection as well as manual URL input
                if (state.url === '/login') {
                    this.router.navigate(['/master/accueil']);
                }
                return true;
            } else {
                // Allow routing to LoginComponent if not logged in
                if (state.url === '/login')
                    return true;
                // Refuse access to specific URL => Redirect to Login
                this.router.navigate(['/login']);
                return false;
            }
        });
}

I did it this way because I could save the state server-side with a Session variable. You need to find your own way to save this state if you want to realize this behavior. Hope this helps



回答2:

You can show popup to confirm logout.

import { Platform, IonicApp } from 'ionic-angular';

  constructor(public platform: Platform, private ionicApp: IonicApp){}

  initializeApp() {
    this.platform.ready().then(() => {
      //back button handle
      this.platform.registerBackButtonAction(() => {
        let ready = true;
        let activePortal = this.ionicApp._loadingPortal.getActive() ||
          this.ionicApp._modalPortal.getActive() ||
          this.ionicApp._toastPortal.getActive() ||
          this.ionicApp._overlayPortal.getActive();

        if (activePortal) { 
          //If any popup is open, dismiss it.
          ready = false;
          activePortal.dismiss();
          activePortal.onDidDismiss(() => { ready = true; });
          return;
        }
        else {
          if (this.nav.canGoBack()) {
            //You can come to parent screen by pressing back button.
            this.nav.pop();
          } else {
            //After coming back to home screen, you can ask confirmation for logout to user.
            this.confirmLogout();
          }
        }
      });
    });
  }

  confirmLogout() {
    let confirm = this.alertCtrl.create({
      title: 'Log out?',
      message: 'Do you want to log out?',
      buttons: [
        {
          text: 'No',
          handler: () => {
            console.log('No clicked');
          }
        },
        {
          text: 'Yes',
          handler: () => {
            navigator['app'].exitApp();
          }
        }
      ]
    });
    confirm.present();
  }