如果用户未登录Angular2 2.0.0-rc.4,则重定向到登录路由

pd *_*had 4 angular2-routing angular

这是我的html文件

<div class="container">
  <h1>Dohatec Data</h1>
  <div class="navLinks">
    <a [routerLink]="['/home']">Home</a>&nbsp;
    <a [routerLink]="['/about']">About-Us </a>&nbsp;
    <a [routerLink]="['/price']">Pricing</a>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的RouterConfig.

const routes: RouterConfig = [
  { path: '', redirectTo: 'home', terminal: true },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutUsComponent },
  { path: 'price', component: PriceComponent },
  { path: 'login', component: LoginComponent }
];
Run Code Online (Sandbox Code Playgroud)

如果用户未登录/ home路由,我想重定向用户.我可以在RouterConfig中完成吗?我不想使用, canActivate: [LoggedInGuard]因为它限制在路线之前

Aks*_*Rao 6

1.将用户存储在本地存储或cookie中,您可以检查用户是否从组件的ngoninit登录.基于此,如果用户未登录,您可以重定向到登录页面.

2.如果用户登录,您可以使服务中的变量成为真,并且基于此,您可以重定向到登录页面.

我希望这是你正在寻找的:)

你的答案 :-

您可以在路由中使用canActivate和canDeactivate属性.首先将名为isLoggedIn的变量设置为false并在登录时将其设置为true,并且可以通过添加canActivate方法来限制用户: -

在你的路线文件中第三个属性:..

canActivate:[Authentication]
Run Code Online (Sandbox Code Playgroud)

并从另一个文件导入身份验证.....

import { CanActivate, Router } from '@angular/router';

export class Authentication implements CanActivate {

constructor(private service: Service, private router: Router) {}


canActivate() {

    if (this.authService.isLoggedIn) { return true; }
    this.router.navigate(['/login']);
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)