3

我已经创建了一个 AuthGuard 服务并为其实现了 CanLoad 接口,如下所示

import { Injectable } from '@angular/core';
import { CanLoad, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanLoad {
  constructor(private router: Router) { }

  canLoad() {
    if (localStorage.getItem('isLoggedin')) {
      return true;
    }
    this.router.navigate(['/auth/login']);
    return false;
  }
}

下面是我的应用路由模块

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './shared/guard/auth.guard';

const routes: Routes = [
  { path: '', loadChildren: './layout/layout.module#LayoutModule', canLoad: [AuthGuard] },
  { path: 'auth', loadChildren: './auth/auth.module#AuthModule' },
  { path: 'not-found', loadChildren: './not-found/not-found.module#NotFoundModule' },
  { path: '**', redirectTo: 'not-found' }
];

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

当我检查浏览器网络选项卡时没有下载文件,我看到一个空白的白页,下面是我在浏览器中看到的警告

platform-browser.js:613 Throttling navigation to prevent the browser from hanging. See https://crbug.com/882238. Command line switch --disable-ipc-flooding-protection can be used to bypass the protection
4

3 回答 3

1

终于解决了这个问题,只需要按如下路线重新排序

const routes: Routes = [
  { path: 'auth', loadChildren: './auth/auth.module#AuthModule' },
  {
    path: '', loadChildren: './layout/layout.module#LayoutModule', canLoad: [AuthGuard],
  },
  { path: 'not-found', loadChildren: './not-found/not-found.module#NotFoundModule' },
  { path: '**', redirectTo: 'not-found' }
];
于 2019-04-30T13:25:15.737 回答
0

你的代码有问题。Guard 仅用于检查您是否有权访问该路由,因此将用户重定向到 Guard 中的不同路由并不理想。

您必须实现 CanActivate 接口而不是 CanLoad 接口

所以你的代码必须改成这个

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) { }

  canActivate() {
    if (localStorage.getItem('isLoggedin')) {
      return true;
    }
    return false;
  }
}
于 2019-04-30T11:21:23.237 回答
0

问题是默认pathMatch设置为'prefix',这意味着每个路径都将匹配通向该模块的路由上的空路径。所以可能的修复是,设置pathMatch: 'full',像这样:

{ path: '', loadChildren: './layout/layout.module#LayoutModule', pathMatch: 'full', canLoad: [AuthGuard], },

或按照您在答案中已经确定的重新排序路线。

于 2019-06-13T14:41:54.633 回答