如果用户已登录,Angular 2重定向 [英] Angular 2 redirect if user is logged in

查看:95
本文介绍了如果用户已登录,Angular 2重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的路由:

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];

AuthGuard

export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private router: Router,
              private authService: AuthService) { }

  canActivate() {
    if (this.authService.isLoggedIn()) {
      return true;
    }
    this.router.navigate(['login']);
    return false;
  }
}

当用户访问网站时,他被重定向到登录页面。当用户尝试未经身份验证访问 / dashboard 路由时,也会发生同样的情况。如果用户已登录,如何将用户重定向到 / dashboard ?例如,当我访问 myapp.com 并登录后,我想重定向到 myapp.com/dashboard

When the user visits the website, he gets redirected to the login page. Same happens when the user tries to access /dashboard route without authentication. How can I redirect the user to /dashboard if he's logged in? For example, when I visit myapp.com and I'm logged in I want to be redirected to myapp.com/dashboard.

推荐答案

在这种情况下,我可能会将所有内容重定向到 DashboardComponent 使用

In this case I would probably redirect everything to DashboardComponent using

{path:``,redirectTo:'dashboard',pathMatch:'full'}

,然后仪表板组件可以确定用户是否登录(由于AuthGuard处于活动状态),如果用户未登录,它将重定向他以登录

and than the dashboard component can determinate if the user is logged in or not (as it has AuthGuard active), and if the user is not logged in it would redirect him to login.

这篇关于如果用户已登录,Angular 2重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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