首页 > 解决方案 > Angular:单击 routerLink 时如何获取 auth.guard.ts 中的 url

问题描述

我想在 auth.guard.ts 文件中获取 URL,同时单击由routerLink. 请参阅下面我的.html文件中的代码:

<li><a href="javascript:void(0)" routerLink="genre" routerLinkActive="active">Genre</a></li>
<li><a href="javascript:void(0)" routerLink="category" routerLinkActive="active">Category</a></li>

这是我的文件中的代码片段auth.guard.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 
  console.log('URL = ' + state.url)
  ...
}

只有刷新浏览器/页面,我才能在控制台中看到 URL。但是,当我单击上面指定的“类别”或“流派”等链接时,控制台什么也没有显示。

下面是我的路由文件:

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';

import { PagesComponent } from './pages.component';
import { AuthGuard } from '../_guards/auth.guard';

const routes: Routes = [{
  path: '',
  component: PagesComponent, canActivate: [ AuthGuard ],
  children: [
      {
        path: 'genre',
        loadChildren: () => import('./genre/genre.module')
          .then(m => m.GenreModule),
      },
      {
        path: 'category',
        loadChildren: () => import('./category/category.module')
          .then(m => m.CategoryModule),
      },
  ]
},

]

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class PagesRoutingModule {
}

标签: angular

解决方案


您能否尝试在子路由以及下面添加 canActivate: [ AuthGuard ]。

children: [
      {
        path: 'genre',
        canActivate: [ AuthGuard ],
        loadChildren: () => import('./genre/genre.module')
          .then(m => m.GenreModule),
      },
      {
        path: 'category',
        canActivate: [ AuthGuard ],
        loadChildren: () => import('./category/category.module')
          .then(m => m.CategoryModule),
      },
  ]

推荐阅读