Angular2:阻止经过身份验证的用户访问特定路由 [英] Angular2: Prevent authenticated users from accessing specific routes

查看:118
本文介绍了Angular2:阻止经过身份验证的用户访问特定路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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,但是他们可以访问关于家庭,登录

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方法,用户还可以转到诸如loginhome之类的路由.我该如何预防呢?

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆