Redirect to login route if the user not logged in

2019-02-18 04:31发布

问题:

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