Ionic 4 从历史记录中删除页面 (Android)

And*_*huk 4 routing android ionic-framework angular

Android 设备在菜单工具栏上有后退按钮。当我登录到我的应用程序并单击该后退按钮以在登录页面上路由时,我想禁用这种可能性。

我想如果用户在登录后点击后退按钮然后我关闭应用程序。这是我用于路由的初始代码。

if (token) {
    this.router.navigate(['/main-tabs/tabs/dashboard'])
} else {
    this.router.navigate(['/login']).then();
}
Run Code Online (Sandbox Code Playgroud)

Eim*_*har 5

我尝试了许多其他答案,但没有一个真正适合我。但是这个有效:

要在注销后禁止登录“返回”到经过身份验证的页面,只需在您的app-routing.module.ts.

{
    path: 'home',
    loadChildren: './home/home.module#HomePageModule',
    canActivate: [LoggedAuthGuard]
}
Run Code Online (Sandbox Code Playgroud)

反之亦然(防止使用后退按钮返回登录页面):

{
    path: 'login',
    loadChildren: './login/login.module#LoginPageModule',
    canActivate: [NotLoggedAuthGuard]
}
Run Code Online (Sandbox Code Playgroud)

而且两者LoggedAuthGuardNotLoggedAuthGuard必须实现CanActivate。示例代码如下(使用Promise,但它也适用于布尔返回):

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'));
  }
}
Run Code Online (Sandbox Code Playgroud)

For the NotLoggedAuthGuard you just returns the opposite of LoggedAuthGuard.

async canActivate() {
    return (await !this.storage.get('access_token'));
}
Run Code Online (Sandbox Code Playgroud)

Hope this helps.