Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 4 Delete Page from History (Android)

Android devices has back button on menu toolbar. I want to disable the possibility when i login to my app and click on that back button to route on login page.

I want if user click on back button after login then i close the app. Here is my initial code for routing below.

if (token) {
    this.router.navigate(['/main-tabs/tabs/dashboard'])
} else {
    this.router.navigate(['/login']).then();
}
like image 905
Andrew Kovalchuk Avatar asked Mar 04 '23 08:03

Andrew Kovalchuk


2 Answers

I've tried many other answers but none of them really works for me. But this one works :

To disallow the login from going 'back' to the authenticated page after logged out, just do something like this in your app-routing.module.ts :

{
    path: 'home',
    loadChildren: './home/home.module#HomePageModule',
    canActivate: [LoggedAuthGuard]
}

The same for the opposite (to prevent going back into login page with back button) :

{
    path: 'login',
    loadChildren: './login/login.module#LoginPageModule',
    canActivate: [NotLoggedAuthGuard]
}

And both LoggedAuthGuard and NotLoggedAuthGuard must implement CanActivate. Sample code as below (with Promise, but it also works with boolean return) :

import { Injectable } from '@angular/core';
import {CanActivate} from "@angular/router";
import {Storage} from "@ionic/storage";

@Injectable({
  providedIn: 'root'
})
export class LoggedAuthGuard implements CanActivate {
  constructor(protected storage: Storage) { }

  async canActivate() {
      return (await !!this.storage.get('access_token'));
  }
}

For the NotLoggedAuthGuard you just returns the opposite of LoggedAuthGuard.

async canActivate() {
    return (await !this.storage.get('access_token'));
}

Hope this helps.

like image 130
Eimihar Avatar answered Mar 12 '23 00:03

Eimihar


This answer provides a solution for removing the login page from the browser's history by replacing it with a page, that the user was navigated to after successful login. It might be a good and quick solution to:

I want to disable the possibility when i login to my app and click on that back button to route on login page.

like image 36
Patronaut Avatar answered Mar 12 '23 01:03

Patronaut