欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular中AuthGuard路由守衛(wèi)的創(chuàng)建使用

 更新時(shí)間:2023年07月31日 10:54:17   作者:JerryWang_汪子熙  
這篇文章主要為大家介紹了Angular中AuthGuard路由守衛(wèi)的創(chuàng)建使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

Angular中的AuthGuard

Angular 中的 AuthGuard 是一個(gè)路由守衛(wèi),它用于保護(hù)某些路由,只有當(dāng)用戶經(jīng)過(guò)身份驗(yàn)證并具有訪問(wèn)權(quán)限時(shí),才允許他們?cè)L問(wèn)。AuthGuard 通常與路由配置一起使用,以確保用戶無(wú)法直接訪問(wèn)需要身份驗(yàn)證的頁(yè)面。

創(chuàng)建

AuthGuard 是一個(gè) Angular 服務(wù),可以使用以下命令來(lái)創(chuàng)建它:

ng g guard auth

上面的命令將生成一個(gè)名為“auth”的 AuthGuard,并將其添加到 src/app/auth.guard.ts 文件中。

auth.guard.ts 文件中的代碼如下所示:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
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): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

在上面的代碼中,AuthGuard 是通過(guò)實(shí)現(xiàn) CanActivate 接口來(lái)定義的。CanActivate 接口包含一個(gè)名為 canActivate() 的方法,該方法決定了當(dāng)用戶嘗試訪問(wèn)受保護(hù)的路由時(shí)應(yīng)該執(zhí)行哪些操作。

在 AuthGuard 中,我們注入了一個(gè)名為 AuthService 的服務(wù)和 Router 對(duì)象。AuthService 用于檢查用戶是否已經(jīng)登錄,而 Router 用于導(dǎo)航到登錄頁(yè)面或者用戶試圖訪問(wèn)的頁(yè)面。在 canActivate() 方法中,我們首先調(diào)用 this.authService.isLoggedIn() 方法來(lái)檢查用戶是否已經(jīng)登錄。如果用戶已經(jīng)登錄,我們返回 true,表示用戶可以訪問(wèn)該路由。否則,我們調(diào)用 this.router.navigate(['/login']) 方法,將用戶重定向到登錄頁(yè)面,然后返回 false,表示用戶無(wú)法訪問(wèn)該路由。

AuthGuard保護(hù)一個(gè)路由

要使用 AuthGuard 來(lái)保護(hù)一個(gè)路由,我們需要在路由配置中將 AuthGuard 添加到 canActivate 屬性中。例如:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

在上面的代碼中,我們將 AuthGuard 添加到了 /dashboard 路由的 canActivate 屬性中,這意味著只有當(dāng)用戶已經(jīng)登錄時(shí)才能訪問(wèn) /dashboard 路由。

以上就是Angular中AuthGuard路由守衛(wèi)的創(chuàng)建使用的詳細(xì)內(nèi)容,更多關(guān)于Angular AuthGuard創(chuàng)建使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論