Redirect to login if the user does not log in Angular2 2.0.0-rc.4
This is my html file
<div class="container">
<h1>Dohatec Data</h1>
<div class="navLinks">
<a [routerLink]="['/home']">Home</a>
<a [routerLink]="['/about']">About-Us </a>
<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 users if they are not registered on the / home route. Can I do this in RouterConfig? I do not want to use canActivate: [LoggedInGuard]because it restricts the route
+4
1 answer
1. Save the user in local storage or in a cookie, and you can check whether the user is registered with him on ngoninit of your component. Based on this, you can redirect to the login page if the user is not logged in.
2. , , u .
, , :)
: -
canActivate canDeactivate .. isLoggedIn false , , canActivate : -
:..
canActivate:[Authentication]
.....
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;
}
}
+6