Angular2:防止经过身份验证的用户访问特定路由 [英] Angular2: Prevent authenticated users from accessing specific routes
问题描述
我在我的 main.ts
文件中定义了一些 routes
:
I've defined some routes
in my main.ts
file:
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
After successful login I want my authenticated users can be able to use specific routes (e.g. dashboard
). And without login they cannot access dashboard
but they can be able to visit about,home,login
我使用 CanActivate
设法限制用户在没有登录的情况下遍历 dashboard
.
I've managed to restrict users traversing the dashboard
without login, using CanActivate
.
canActivate(): boolean {
if (this.authService.isLoggedIn()) {
return true;
}
this.router.navigateByUrl('/login');
return false;
}
但是使用这些路由和成功登录后的CanActivate
方法,用户还可以转到像login
、home
这样的路由.我怎样才能防止这种情况?
But Using those routes and the CanActivate
approach after successful login, users are also able to goto routes like login
, home
. How can I prevent that?
注意我正在使用 angular2 RC4.
N.B. I'm using angular2 RC4.
推荐答案
我做了一些研究,看看是否可以否定"一个守卫,但似乎你必须制作另一个与你的守卫相反的守卫.喜欢:
I made some researches to see if it's possible to "negate" a guard but seems like you have to make another guard which is the opposite of your guard. Like :
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();
}
}
也将它添加到您的引导函数中,您就大功告成了.你只需要在你的路线上做:
Add it in your bootstrap function as well and you are all set. You just have to do in your routes :
{ path: 'login', component: LoginComponent, canActivate: [PreventLoggedInAccess] },
这篇关于Angular2:防止经过身份验证的用户访问特定路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!