Angular项目路由配置与导航守卫

1:一个项目的所有组件如下 测试案例:

    AppComponent,
    HomeComponent,
    TopComponent,
    MenuComponent,
    ProductComponent,
    BodyComponent,
    MydialogComponent,
    MybooksComponent,
    StudentComponent,
    TeacherComponent,
    WelcomeComponent,
    LoginComponent

2:home 整体布局

<div class="grid">
    <div class="col-12 bg-gray-300" style="height: 20%">
        <app-top></app-top>
    </div>
    <div class="col-2 bg-blue-100 h-full" style="position: relative;">
        <app-menu style="height: 100%;"></app-menu>
    </div>
    <div class="col-10">
        <app-body></app-body>
    </div>
</div>

3: AppComponent

<router-outlet />

4:body 组件下

<router-outlet></router-outlet>

5:app-routing.module.ts 路由内容:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from "./components/home/home.component";
import { TopComponent } from './components/top/top.component';
import { MenuComponent } from './components/menu/menu.component';
import { ProductComponent } from './components/product/product.component';
import { BodyComponent } from './components/body/body.component';

import { StudentComponent } from './components/student/student.component';
import { TeacherComponent } from './components/teacher/teacher.component';
import { MybooksComponent } from './components/mybooks/mybooks.component';
import { WelcomeComponent } from './components/welcome/welcome.component';
import { LoginComponent } from './components/login/login.component';

//导入路由导航守卫服务
import { RouterAopService } from './services/router-aop.service';
const routes: Routes = [

  { path: '', redirectTo: '/home/body/welcome', pathMatch: "full" },//首页输入 localhost:4200 ,就可以自动跳转到欢迎页面
  { path: "login", component: LoginComponent },
  { path: "home", redirectTo: "/home/body/welcome", pathMatch: "full" }, //localhost:4200/home ,就可以自动跳转到欢迎页面
  {
    path: "home", component: HomeComponent,
   
    children: [
      { path: "top", component: TopComponent },
      { path: "menu", component: MenuComponent },
      {
        path: "body", component: BodyComponent,
        children: [
          { path: "", redirectTo: "/home/body/welcome", pathMatch: "full" }, //localhost:4200/home/body ,就可以自动跳转到欢迎页面
          { path: "welcome", component: WelcomeComponent },
          { path: "product", component: ProductComponent,canActivate: [RouterAopService] },
          { path: "student", component: StudentComponent },
          { path: "book", component: MybooksComponent },
          { path: "teacher", component: TeacherComponent }
        ]
      }   
    ]
  },
  { path: "**", redirectTo: "login" } // 路哟找不到或者乱输入的地址
];

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

6:========导航守卫的处理===========

7:创建导航守卫的服务service

ng g s services/router-aop
RouterAopService 服务内容如下:


import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RouterAopService implements CanActivate {

  constructor(private router: Router) { }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    : boolean | Observable<boolean> | UrlTree | Promise<boolean | UrlTree> {

    // 实现你的守卫逻辑
    const isAuthenticated = localStorage.getItem("logininfo");
    if (!isAuthenticated) {
      this.router.navigate(["/login"]);
      return false;
    }
    return true; // 示例返回值
  }
}

8:登录html

<div class="myre">
    <div class="myab">
        <div class="field">
            <label for="Username"></label>
            <span class="p-input-icon-left">
                <i class="pi pi-user"></i>
                <input type="text" id="Username" pInputText placeholder="Username" [(ngModel)]="Username"/>
            </span>
            <small *ngIf="!Username" class="p-error">Username is required</small>
      
        </div>

        <div class="field">
            <label for="Pwd"></label>
            <span class="p-input-icon-left">
                <i class="pi pi-lock"></i>
                <input type="text" id="Pwd" pInputText  [(ngModel)]="Pwd" placeholder="pwd"/>
            </span>
            <small *ngIf="!Pwd" class="p-error">Password is required</small>
        </div>

        <div class="flex flex-row-reverse flex-wrap" style="text-align: end;">
            <div class="flex"><button type="button" pButton label="login" (click)="loginNow()"></button></div>
        </div>
    </div>
</div>
<p-toast position="top-center"></p-toast>

<!--测试 primeflex 的flex布局 <div class="flex flex-row flex-wrap">
    <div class="flex bg-blue-100 p-4 m-2">1</div>
    <div  class="flex  bg-gray-200 p-4  m-2 ">2</div>
    <div  class="flex  bg-red-100 p-4  m-2 ">3</div>
</div> -->

9:登录js 逻辑

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { MessageService } from 'primeng/api';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss',
  providers: [MessageService]
})
export class LoginComponent implements OnInit {
  Username: string;
  Pwd: string;
  constructor(private router: Router,
    private messageService: MessageService
  ) {
    this.Username = "";
    this.Pwd = "";

  }
  ngOnInit(): void {

  }
  loginNow() {
    if (this.Username == "Admin" && this.Pwd == "123") {
      var data={useName:this.Username, usePwd:this.Pwd};
      localStorage.setItem("logininfo",JSON.stringify(data));
      
      this.router.navigate(["/home/body"]);
    } else {
      this.messageService.add({ severity: 'error', summary: 'Error', detail: 'UserName Or Pwd is Error' })
    }
  }
}

10:测试路由地址

首先不登录直接访问 home/body/product路由,地址回车后被重定向到login页面,
输入正确的账号密码后再访问product 发现可以正常访问了,浏览器中F12 找到对应的 储存可以,
删掉后刷新改地址后,又被重新定位到login页面,到此整个逻辑效果ok

11:测试效果图

 

posted @ 2024-06-18 11:55  天天向上518  阅读(18)  评论(0编辑  收藏  举报