首页 文章

限制历史状态更改以防止浏览器挂起

提问于
浏览
9

这是一个初学角度问题 .

我的Angular应用程序包含多个功能模块 . 我通过从angular-cli生成guard来使用authguard,然后在我的app-routing模块中使用CanActivate,如下所示:

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

const routes: Routes = [
{path:'login',loadChildren:'./login/login.module#LoginModule',canActivate: 
[AuthGuard]},
{path:'home', loadChildren:'./user/user.module#UserModule',canActivate: 
[AuthGuard]},
{path:'cart', 
loadChildren:'./cart/cart.module#CartModule',canActivate:[AuthGuard]},
 {path:'customer',loadChildren:'./customer/customer.module#CustomerModule',canActivate:[AuthGuard]}
];

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

在我的身份验证中,我写了条件以防止用户访问未经授权的路由:

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

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean 
{
  if(["user","customer","cart"].indexOf(localStorage.pass)>=0){alert("auth 
guard!");
return true;}
else 
this.router.navigate(['/login']);
}
}

构建之后,我在重建期间检测到的loadChildren中的重复路径中收到警告警告 . 我们将检测到最新版本并覆盖它以节省重建时间 . 您应该执行完整版本以验证您的路由不重叠 .

所以我用Google搜索并找到了this comment,在最后一条路径上添加逗号后警告消失了 .

但之后我登录到我的应用程序并在控制台中显示以下消息:限制历史状态更改以防止浏览器挂起和应用程序卡住 .

有什么想法吗?

编辑:我最终通过使用'canLoad'代替'canActivate'来实现它,但如果有人能够提供有关此问题的更多见解,那将会很棒 .

5 回答

  • 2

    删除登录路径中的canActivate . 这是循环 .

  • 20

    在我的情况下,我有一个无限循环 .

    如果您在路由中使用通配符(*),请确保它是列表中的最后一个 . 您应该首先定义所有其他路线 .

    { path '/', component: HomeComponent },
    { path 'profile', component: ProfileComponent },
    // All your other routes should come first    
    { path: '404', component: NotFoundComponent },
    { path: '**', component: NotFoundComponent }
    
  • 0

    检查Gaurd中的一个路径是尝试加载多次作为循环 . 这是我的问题..

  • 3

    我最近有一个类似的问题,看着你的代码我注意到两件事: - 你将Authguard放在登录路径中,即使是访问路径 . - 您不会在警卫中返回负值,只需重定向即可 .

    尝试修复这两件事,也许它会有所帮助 . 当我在否定的情况下没有返回任何值时,我遇到了问题,这导致我遇到了同样的问题 .

  • 3

    我一整天都有这个问题 . 发现这个official post,但没有解释清楚这里的问题 .

    我正在调试这个问题,我发现我的canActivate函数有一个错误,试图访问一个没有初始化的对象的属性 . 我没有意识到这一点,并且在此错误之后(您将无法在控制台中看到),“限制历史状态更改以防止浏览器挂起”的问题开始在lopp中触发...

    只需我2美分:确保你在函数canActivate或canDeactivate中没有任何错误 .

    希望它能帮助别人!

    干杯

相关问题