角度6:空路径绕过身份验证保护

时间:2018-07-31 22:57:14

标签: angular angular-routing auth-guard

我正在尝试使用Angular路由器,并且在空路径上遇到问题。这是我的路线:

const routes: Routes = [

    { path: 'feed', loadChildren: './feed/feed.module#FeedModule', canLoad: [AuthGuardService] },
    { path: 'login', component: LoginPage },
    { path: 'register', component: RegisterPage },
    { path: '', redirectTo: '/feed', pathMatch: 'full' },
    { path: '**', redirectTo: '/' }
];

我的AuthGuardService有一个canLoad方法,该方法始终返回false并重定向到'/ login'路径:

...
@Injectable()
export class AuthGuardService implements CanLoad {
  constructor(private router: Router) {
  }
  canLoad(route: Route): boolean {

    this.router.navigate([ '/login' ]);
    return false;
  }
}

当我进入'localhost:4200 / feed'时,我被重定向到'/ login'。

但是,如果我转到“ localhost:4200 /”,则会忽略身份验证保护并显示供稿模块的组件。

你知道为什么吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

在我的方案中,我有一个有效的代码。进行检查,如果它可以帮助您。

可以使用canActivate代替canLoad。

canActivate 用于防止未经授权的用户
canLoad 用于阻止应用程序的整个模块

在下面的示例中,如果要使用canLoad代替,可以将 canActivate 替换为 canLoad

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

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

在编写路线时,您可以如下定义。

{ path: 'newLeaveRequest', component: NewLeaveRequestComponent, canActivate: [AuthGuard]},
{ path: 'pastLeaveRequests', component: PastLeaveRequestComponent, canActivate: [AuthGuard]},

在app.module.ts中 在提供程序中定义AuthGuard。

答案 1 :(得分:0)

我已经解决了我的问题,对于您的延迟,我们深表歉意: 我需要使用一个组件并使用canActivate才能加载子模块

{
    path: 'feed',
    canActivate: [ AuthGuard ],
    component: FeedComponent,
    children: [
        {
      path: '',
      loadChildren: () => FeedModule
}]}

为孩子延迟加载也可以!

干杯!

相关问题