您好,登錄后才能下訂單哦!
小編給大家分享一下angular9中路由守衛(wèi)的使用方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
路由守衛(wèi)是什么
任何用戶都能在任何時候?qū)Ш降饺魏蔚胤?。但有時候出于種種原因需要控制對該應(yīng)用的不同部分的訪問??赡馨ㄈ缦聢鼍埃?/p>
該用戶可能無權(quán)導(dǎo)航到目標(biāo)組件。
可能用戶得先登錄(認證)。
在顯示目標(biāo)組件前,你可能得先獲取某些數(shù)據(jù)。
在離開組件前,你可能要先保存修改。
你可能要詢問用戶:你是否要放棄本次更改,而不用保存它們?
相關(guān)推薦:《angular教程》
組件的創(chuàng)建
1、home組件創(chuàng)建
2、login組件創(chuàng)建
3、home下的first和second子組件
守衛(wèi)路由相關(guān)核心代碼
routing中每個路由都是對所有人開放的。這些新的管理特性應(yīng)該只能被已登錄用戶訪問。
編寫一個 CanActivate() 守衛(wèi),將正在嘗試訪問管理組件匿名用戶重定向到登錄頁。
1.1 在auth 文件夾下,新建一個auth.service.ts文件,模擬有關(guān)登錄的請求服務(wù),實際場景一般是將后臺token保存在cookie中.
import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { tap, delay } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class AuthService { isLoggedIn = false; //默認未登錄 // 記錄登錄之后,需要跳轉(zhuǎn)到原來請求的地址 redirectUrl: string; // 登錄 login(): Observable<boolean> { return of(true).pipe( delay(1000), tap(val => this.isLoggedIn = true) ); } // 登出 logout(): void { this.isLoggedIn = false; } }
1.2 在 auth 文件夾下,新建一個auth.guard.ts文件
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { let url: string = state.url return this.checkLogin(url); } checkLogin(url: string): boolean { if (this.authService.isLoggedIn) { return true; } // 保存原始的請求地址,登錄后跳轉(zhuǎn)到該地址 this.authService.redirectUrl = url; // 未登錄,跳轉(zhuǎn)到登錄頁面 this.router.navigate(['/login']); return false; } }
在路由中使用守衛(wèi)
在app-routing.module.ts文件下使用
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AuthGuard } from './auth/auth.guard'; import { LoginComponent } from './login/login.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'home', loadChildren: () => import('./home/home.module') .then(mod => mod.HomeModule), canActivate: [AuthGuard], // 守衛(wèi)路由 } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
以上是“angular9中路由守衛(wèi)的使用方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。