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:測試效果圖