代码之家  ›  专栏  ›  技术社区  ›  Varun Sukheja

Angular7:CanLoad Auth guard挂起浏览器

  •  0
  • Varun Sukheja  · 技术社区  · 5 年前

    我已经创建了一个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
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Varun Sukheja    5 年前

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

    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
  •   user4851087 user4851087    5 年前

    您必须实现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;
      }
    }
    
        3
  •  0
  •   Domen Jakofčič    5 年前

    pathMatch 设置为 'prefix' 空路 在通往该模块的路线上。因此,可能的修复方法是,设置 pathMatch: 'full' ,例如:

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

    in your answer.