gpt4 book ai didi

Angular 2 : Prevent authenticated users from accessing specific routes

转载 作者:太空狗 更新时间:2023-10-29 17:00:47 25 4
gpt4 key购买 nike

我在我的 main.ts 文件中定义了一些 routes:

const routes: RouterConfig = [
{ path: '', component: HomeComponent },
{ path: '', redirectTo: 'home', terminal: true },
{ path: 'dashboard', component: DashboardComponent, canActivate: [LoggedInGuard] },
{ path: 'login', component: LoginComponent },
{ path: 'about', component: AboutComponent }
];

成功登录后,我希望经过身份验证的用户能够使用特定路由(例如 dashboard)。如果没有登录,他们将无法访问 dashboard,但他们可以访问 about,home,login

我已经设法限制用户在没有登录的情况下遍历仪表板,使用CanActivate

canActivate(): boolean {
if (this.authService.isLoggedIn()) {
return true;
}
this.router.navigateByUrl('/login');
return false;
}

但是使用这些路由和成功登录后的 CanActivate 方法,用户还可以转到 loginhome 等路由。我怎样才能防止这种情况发生?

注意我正在使用 angular2 RC4。

最佳答案

我做了一些研究,看看是否有可能“否定”一个守卫,但似乎你必须制造另一个与你的守卫相反的守卫。喜欢:

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthService } from './your-auth.service';

@Injectable()
export class PreventLoggedInAccess implements CanActivate {

constructor(private authService: AuthService) {}

canActivate() {
return !this.authService.isLoggedIn();
}
}

也将它添加到您的引导函数中,一切就绪。你只需要在你的 route 做:

{ path: 'login', component: LoginComponent, canActivate: [PreventLoggedInAccess] },

关于 Angular 2 : Prevent authenticated users from accessing specific routes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com