Angular Stock Route Guards (Day31)

虽然铁人赛比完了,但是我依然会把这个专案继续写下去,如果还没看之前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:

  • Perhaps the user is not authorized to navigate to the target component.
  • Maybe the user must login (authenticate) first.
  • Maybe you should fetch some data before you display the target component.
  • You might want to save pending changes before leaving a component.
  • You might ask the user if it's OK to discard pending changes rather than save them.

简单来说就是我们有些页面不想让没有经过身分验证的使用者使用,又或是

我们想要使用者确认是否要舍弃目前页面上输入的资料

因此我们会设下一些限制

A guard's return value controls the router's behavior:

  • If it returns true, the navigation process continues.
  • If it returns false, the navigation process stops and the user stays put.
  • If it returns a [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 就会发现被转导到登入页了喔


<<:  【Day21】:客制化的PWM输出

>>:  用 Python 畅玩 Line bot - 19:加入与移除好友

Day 28:「今天几月几号啊?」- 简易日历

「今天是几月几号啊?」 今天是 ... 等等! 不准看电脑上的! 你先等我造出一个,我们要看日期 ...

[今晚我想来点 Express 佐 MVC 分层架构] DAY 27 - 用 Webpack 打包 Express

Webpack 是什麽? 图片来源 Webpack 是一个打包工具,经常用於前端领域,能够将各个依赖...

重温-基本&UI

创立一个属於自己的App,那就需要两个必须的部份,设备与知识。 自己所使用的设备为Apple Mac...

[前端暴龙机,Vue2.x 进化 Vue3 ] Day6. 模板语法

模板语法 在上一篇我们已经完成了我们第一个 Vue 建出来的 Hello Vue 网页,其中我们有学...

解决宝塔强制绑定账号

现在新版本的宝塔面板强制绑定宝塔官网账号,否则就无法继续使用面板。 临时的解决办法就是我们在URL目...