虽然铁人赛比完了,但是我依然会把这个专案继续写下去,如果还没看之前Angular Stock的朋友,
麻烦帮我点连结进去看。
好,接下来我们遇到一个问题在於说,不管有没有登入的人,都可以进入我们的主页(index.html)
因此我们需要利用Route Guards来阻挡未符合验证规则的人进入页面
那什麽是Route Guards呢?
At the moment, any user can navigate anywhere in the application any time, but sometimes you need to control access to different parts of your application for various reasons, some of which might include the following:
简单来说就是我们有些页面不想让没有经过身分验证的使用者使用,又或是
我们想要使用者确认是否要舍弃目前页面上输入的资料
因此我们会设下一些限制
A guard's return value controls the router's behavior:
true
, the navigation process continues.false
, the navigation process stops and the user stays put.[UrlTree](https://angular.io/api/router/UrlTree)
, the current navigation cancels and a new navigation is initiated to the [UrlTree](https://angular.io/api/router/UrlTree)
returned.在此次我们会针对navigation process进行修改
首先我们先在service里新增auth.service
ng g s /service/auth
接着新增一个shares资料夹,并且在里面新增auth.guard
ng g guard /shares/auth
然後实作auth.service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() {}
//检查sessionStorage的token有没有值
checkIsLogin(): boolean {
const token = sessionStorage.getItem('token') || '';
if ( token ){
return true;
}
return false;
}
}
然後在auth.guard使用
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../service/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private rooter: Router){
}
//CanActivate 所需要实作的方法
canActivate(): boolean{
if (this.authService.checkIsLogin()){
return true;
}
//无法通过验证的请求转到loginComponent
this.rooter.navigate(['login']);
return false;
}
}
在appModule上面修改设定加上
const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', component: LoginComponent },
{ path: 'index', component: IndexComponent, canActivate: [AuthGuard] },
{ path: 'exchange/getStockDayAll', component: DailyTranctionStockComponent, canActivate: [AuthGuard] },
{ path: '**', component: ErrorComponent }, // 万用路由,不可设在前面
];
接着直接在网址输入http://localhost:4200/main 就会发现被转导到登入页了喔
>>: 用 Python 畅玩 Line bot - 19:加入与移除好友
「今天是几月几号啊?」 今天是 ... 等等! 不准看电脑上的! 你先等我造出一个,我们要看日期 ...
Webpack 是什麽? 图片来源 Webpack 是一个打包工具,经常用於前端领域,能够将各个依赖...
创立一个属於自己的App,那就需要两个必须的部份,设备与知识。 自己所使用的设备为Apple Mac...
模板语法 在上一篇我们已经完成了我们第一个 Vue 建出来的 Hello Vue 网页,其中我们有学...
现在新版本的宝塔面板强制绑定宝塔官网账号,否则就无法继续使用面板。 临时的解决办法就是我们在URL目...