Angular7:CanLoad Auth Guard挂起浏览器

时间:2019-04-30 10:35:40

标签: angular routing angular-routing angular-canload

我已经创建了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

3 个答案:

答案 0 :(得分: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;
  }
}

答案 1 :(得分:0)

最终解决了该问题,只需按以下路线重新排序

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' }
];

答案 2 :(得分:0)

问题在于默认的pathMatch设置为'prefix',这意味着每条路径都将在通往该模块的路由上匹配空路径。因此,可能的解决方法是像这样设置pathMatch: 'full'

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

或按照已经确定的in your answer.

重新排序路线