In this article, I will learn how to redirect one page to other page and also discuss how to use the AuthGuard and CanActivate in Angular 5 applications.
Three options are available to redirect page in Angular 5 –
1. Imperatively redirect the user in AppComponent
2. Use the route data property
3. Use a CanActivate guard
The AuthGuard should call an application service that can login a user and retain information about the current user.
Options 1 – Imperatively redirect the user in AppComponent
@Component({
selector: 'app-root',
template: `.....`
})
export class AppComponent {
constructor(private _authService: AuthService, _router: Router) {
if (_authService.isLoggedIn()) {
_router.navigate(['user']);
}
}
}
This is not good practice and I will not recommend using this options.
Options 2 - Use the route data property
This is the best solution and used by many expert programmers. You can simply add some metadata in the routes declaration to indicate that - “this route requires that the user must be loggedIn”.
const APPROUTES: Routes = [
{path: 'dashboard', component: AppComponent, data:{requiresLogin: true}},
{path: 'user', component: UserComponent, data:{requiresLogin: true}}
];
This is the best approach to redirect if not logged in and I will recommend to this option.
Options 3 -Use a CanActivate guard
Firstly add a CanActivate guard to all the routes that require the user to be logged in and my guard is called AuthGuardand see the following example –
@NgModule({
declarations: [
AppComponent,
LoginComponent,
UserComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot([
{ path: '', component: AppComponent, pathMatch: 'full', canActivate: [AuthGuard]},
{ path: 'user', component: UserComponent, canActivate: [AuthGuard]},
{ path: 'login', component: LoginComponent}])
],
providers: [EmployeeService, ValidationService,
AuthenticationService, UserService],
bootstrap: [AppComponent]
})
export class AppModule { }
And
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {Router} from '@angular/router';
import { AuthServiceService } from './auth-service.service';
@Injectable()
export class AuthGuard implements CanActivate {
//constructor initialization
constructor(private authService: AuthServiceService, private route: Router){ }
//can Activate Route
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(this.authService.isLoggednIn()){
this.route.navigate(["user"]);
return true;
}else{
return false;
}
}
}
This is also best approach to redirect if not logged in and this one is also recommend to this option.
0 comments:
Post a Comment