本文摘自PHP中文网,作者青灯夜游,侵删。
本篇文章给大家介绍一下Angular路由守卫的使用。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
路由守卫是什么
任何用户都能在任何时候导航到任何地方。但有时候出于种种原因需要控制对该应用的不同部分的访问。可能包括如下场景:
该用户可能无权导航到目标组件。
可能用户得先登录(认证)。
在显示目标组件前,你可能得先获取某些数据。
在离开组件前,你可能要先保存修改。
你可能要询问用户:你是否要放弃本次更改,而不用保存它们?
相关推荐:《angular教程》
组件的创建
1、home组件创建
2、login组件创建
3、home下的first和second子组件

守卫路由相关核心代码
routing中每个路由都是对所有人开放的。这些新的管理特性应该只能被已登录用户访问。
编写一个 CanActivate() 守卫,将正在尝试访问管理组件匿名用户重定向到登录页。
1.1 在auth 文件夹下,新建一个auth.service.ts文件,模拟有关登录的请求服务,实际场景一般是将后台token保存在cookie中.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import { Injectable } from '@angular/core' ;
import { Observable, of } from 'rxjs' ;
import { tap, delay } from 'rxjs/operators' ;
@Injectable({
providedIn: 'root' ,
})
export class AuthService {
isLoggedIn = false;
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文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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; }
this.authService.redirectUrl = url;
this.router.navigate([ '/login' ]);
return false;
}
}
|
在路由中使用守卫
在app-routing.module.ts文件下使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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],
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
|
最后的结尾
一般路由守卫与拦截器一起使用,感兴趣可以了解一下.
更多编程相关知识,请访问:编程视频!!
以上就是浅谈angular9中路由守卫的用法的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
浅谈angular9中拦截器的用法
浅谈angular9中路由守卫的用法
vue路由守卫有哪三种类型
vue路由守卫哪几种?
更多相关阅读请进入《angular9》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 浅谈angular9中路由守卫的用法