A路由守衛

1、先創建個服務

ng generate service services/guard

2、服務裏面寫

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';

@Injectable({providedIn: 'root'})
export class GuardService implements CanActivate {
  constructor() { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    
    let user=JSON.parse(localStorage.getItem('userId'));
    
    console.log(user)
    if(!user){
      return false;
    }
    return true;
  }
}
//true的時候可以通過 false的時候不給通過

3、appModules上寫

import { GuardService } from './services/guard.service';

const routes:Routes=[
  {path:'',redirectTo:'flash',pathMatch:'full'},
  {path:'flash',component:FlashComponent},
  {path:'main',component:MainComponent,children:[
    {path:'',redirectTo:'home',pathMatch:'full'},
    {path:'home',component:HomeComponent},
    {path:'category',component:CategoryComponent},
    {path:'cart',component:CartComponent},
    {path:'mine',component:MineComponent,canActivate:[GuardService]},
    {path:'search',component:SearchComponent},
    {path:'afterSearched',component:AfterSearchedComponent},
    {path:'bookDetail',component:BookDetailComponent},
    {path:'login',component:LoginComponent},
    {path:'borrowRecords',component:BorrowRecordsComponent},
  ]},
  {path:'mineMes',component:MineMesComponent}
]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章