Introducción a la protección de enrutamiento ionic4 (4)

判断用户是否登录 , 在进入购物车和个人中心 界面的时候, 如果用户没有登录, 需要让用户先进入登录界面
创建守卫
ionic g guard guard/loginGuard 
CanActivate : 路由进入前守卫
canActivateChild :路由进入子组件守卫
CanDeactivate :路由离开守卫
CanLoad :是否加载模块


CanActivate 
state.url 获取要跳转的路由 存到sessionStorage里 当登录成功之后直接跳到这个路由提升用户体验度
import {
    
     Injectable } from '@angular/core';
import {
    
     CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import {
    
     Observable } from 'rxjs';
import {
    
     NavController } from '@ionic/angular';
@Injectable({
    
    
  providedIn: 'root'
})
export class LoginGuardGuard implements CanActivate {
    
    
  constructor(private nav: NavController){
    
    }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    
    
    const token = sessionStorage.getItem('token');
    if (token == null || token === undefined){
    
    
        sessionStorage.setItem('historyUrl', state.url);
        this.nav.navigateForward('login');
        return false;
    }
    return true;
  }
}
CanDeactivate 多用于内容很多的表单里
nextState.url 获取要跳转的路由 存到sessionStorage里 如果用户确认要离开就跳转到这个路由
import {
    
     Injectable } from '@angular/core';
import {
    
     CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import {
    
     Observable } from 'rxjs';
import {
    
     AlertController , NavController } from '@ionic/angular';
import {
    
     async } from '@angular/core/testing';
@Injectable({
    
    
  providedIn: 'root'
})
export class LeaveGuardGuard implements CanDeactivate<unknown> {
    
    
  nextUrl: string;
  constructor(public alertController: AlertController, private nav: NavController){
    
    
  }
  canDeactivate(
    component: unknown,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    
    
    const isSave = sessionStorage.getItem('isSave');
    this.nextUrl = nextState.url;
    if (isSave == null || isSave === undefined){
    
    
        this.presentAlertConfirm();
        return false;
    }
    return true;
  }
  async presentAlertConfirm(){
    
    
    const alert = this.alertController.create({
    
    
    cssClass: 'my-custom-class',
    header: '提示信息!',
    message: '当前有消息未保存是否确认退出',
    buttons: [
      {
    
    
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => {
    
    
        }
      }, {
    
    
        text: '确定',
        handler: () => {
    
    
          console.log(this.nextUrl);
          sessionStorage.setItem('isSave', 'isSave');
          this.nav.navigateForward(this.nextUrl);
        }
      }
    ]
  });
    (await alert).present();
}
}

> 不管是路由进入守卫还是路由离开守卫必须返回一个boolean对象 不然会形成阻塞

Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/qq_31182399/article/details/108740277
Recomendado
Clasificación