首页 > 其他分享 >Angular项目路由配置与导航守卫

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

时间:2024-06-18 12:00:05浏览次数:18  
标签:body home component 守卫 import path login 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:测试效果图

 

标签:body,home,component,守卫,import,path,login,Angular,路由
From: https://www.cnblogs.com/Fengge518/p/18252758

相关文章

  • 代理浏览器中的智能路由实现方法(动态ip代理)
    在数字化时代,网络浏览的流畅性和稳定性成为了用户关注的焦点。代理浏览器作为连接用户与网络世界的桥梁,其智能路由功能的实现对于提升用户体验至关重要。本文将从五个板块探讨如何在代理浏览器上实现智能路由,以期为网络冲浪者带来更加顺畅的上网体验。极光HTTP注册即送1万IP,......
  • 无线传感网路由VBF协议和DBR协议的MATLAB性能仿真
    1.程序功能描述       无线传感网路由VBF协议和DBR协议的MATLAB性能仿真.将两个协议在能量消耗,存活节点等方面进行比较. 2.测试软件版本以及运行结果展示MATLAB2022a版本运行   3.核心程序forc=1:n%计算最接近的cluster个节点dd(c)=sqrt......
  • Angular 18+ 高级教程 – Memory leak, unsubscribe, onDestroy
    何谓 MemoryLeak?Angular是SPA(Single-pageapplication)框架,用来开发SPA。SPA最大的特点就是它不刷新页面,不刷新就容易造成memoryleak。举个例子:有一个页面A,我们写了一个setInterval执行一些代码(比如autoplay幻灯片)。当用户离开页面A去页面B时,传统网......
  • OSPF 动态路由协议(思科、华为)
    #交换设备OSPF动态路由协议一、基本概念1.中文翻译:开放式最短路径优先路由协议(openshortestpathfirst),是一个内部网关路由协议(一个自治系统内)2.也称为:链路状态路由协议:在单一区域内的路由器是向相邻路由器发送链路状态信息【包含接口IP地址和子网掩码、网络类型、该链......
  • 华为----RIP- RIP路由协议基本配置
    08、RIP8.1RIP路由协议基本配置8.1.1原理概述RIP(RoutingInformationProtocol,路由协议)作为最早的距离矢量IP路由协议,也是最先得到广泛使用的一种路由协议,采用了Bellman-Ford算法,其最大的特点就是配置简单。RIP协议要求网络中每一台路由器都要维护从自身到每一个目......
  • 【组播优化】基于蚁群算法求解QOS费用延时组播路由优化问题附Matlab代码
     ✅作者简介:热爱科研的Matlab仿真开发者,修心和技术同步精进,代码获取、论文复现及科研仿真合作可私信。......
  • 【计算机网络仿真实验-实验2.7】单臂路由
    实验2.7单臂路由1.实验拓扑图2.测试连通性测试PC1PC2PC3之间的连通性无法ping通,因为它们处在不同的网段,而二层交换机不具备路由功能,因此没办法接通3.在交换机上创建vlan10,并将端口0/2划分到vlan10中Switch>enableSwitch#configureterminal......
  • Gateway内网关的详细使用说明,包含由于版本问题、依赖问题引起的动态路由转发问题的详
    资料的连接官方文档https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/en-us/index.html基本的概念相关属性Route:一个Route由路由ID(用来绑定哪一个微服务),转发URI(转移的目标URL),多个Predicates以及多个Filters构成。Gateway上可以配置多个Rou......
  • 静态路由综合实验
    1.除R5的环回地址固定以外,整个其他所有网段基于192.168.1.0/24进行合理的ip地址划分2.R1-R4每个路由器存在两个环回接口,用于模拟连接PC网段;地址也在192.168.1.0/24这个网络范围内,R3下面PC通过DHCP获取一个合法的地址3.R1-R4上不能直接编写到达5.5.5.0/24的静态路由,但依然可以访......
  • flask路由系统、偏函数、CBV、模板、请求响应、session、请求扩展
    路由系统1代码演示23fromflaskimportFlask45app=Flask(__name__)67app.debug=True8#路由基本使用9#@app.route('/',methods=['GET'])10#@app.get()11#@app.post()12defindex(name):13print(name)14return&......