Redirect to login route if the user not logged in Angular2 2.0.0-rc.4

妖精的绣舞 提交于 2019-12-01 05:05:55

问题


This is my html file

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

This is my 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 }
];

I want to redirect the users if they are not loggedin in the /home route. Can I do it in the RouterConfig? I dont want to use canActivate: [LoggedInGuard] because it restricts before the route


回答1:


1.store the user in local storage or cookie and you can check if the user is logged in from there on ngoninit of your component.. on basis of this you can redirect to login page if user is not logged in.

2.you can make a variable in service to be true if user is logged in and on basis of this u can redirect to login page .

i hope this is what u are searching for :)

YOUR ANSWER :-

You can use a canActivate and canDeactivate property in your routes.. first of all set a variable named isLoggedIn as false and make it true on login and u can restrict the user by this by adding canActivate method as :-

in your routes file third property :..

canActivate:[Authentication]

and import authentication from another file .....

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;
  }
}


来源:https://stackoverflow.com/questions/38366340/redirect-to-login-route-if-the-user-not-logged-in-angular2-2-0-0-rc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!