In this tutorial you learn How to Implementing Auth Guard with Component less Route in Angular 5?
Let’s start how to Generate Guard, I am using Angular CLI command for generating Auth Guard on Angular 5 applications.
In this article, we take a look with few of the different types of guards and how to implement them for specific use-
1. Maybe the user must authenticate and then login in the app.
2. If user has logged in but is not authorized to navigate to the target component.
3. We might ask the user if its ok to discard pending changes rather than save them.
There are 5 types of Route Guards we use in Angular.
- CanActivate
This helps to decide whether the route can be activated or not.
- CanActivateChild
This helps to decide whether child routes can be activated or not.
- CanDeactivate
This helps to decide whether the route can be deactivated or not. Generally, this is used to warn a user if they are navigating from the component.
- Resolve
This performs route data retrieval before any activation of the route.
- CanLoad
Checks to see if the user can navigate to the module which is lazily loaded.
The Auth Guard implementation is quite simple and Auth Guard CLI command is –
ng generate guard auth
Why Use Auth Guard in Angular 5?
The Auth Guard is used to redirect the user to the page they landed on before being forced to login.
D:\Angular\AngularMaterial>ng generate guard auth
create src/app/auth.guard.spec.ts (346 bytes)
create src/app/auth.guard.ts (401 bytes)
auth.guard.ts –
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return true;
}
}
And
auth.guard.spec.ts –
import { TestBed, async, inject } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
describe('AuthGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AuthGuard]
});
});
it('should ...', inject([AuthGuard], (guard: AuthGuard) => {
expect(guard).toBeTruthy();
}));
});
Now, we generate the login component for using angular gourd –
D:\Angular\AngularMaterial>ng g component login
create src/app/login/login.component.html (24 bytes)
create src/app/login/login.component.spec.ts (621 bytes)
create src/app/login/login.component.ts (265 bytes)
create src/app/login/login.component.css (0 bytes)
update src/app/app.module.ts (394 bytes)
And the app.module.ts looks like –
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule, FormGroup} from '@angular/forms';
import {RouterModule} from '@angular/router';
//MY COMPONENTS
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{ path: '', component: AppComponent, pathMatch: 'full' },
{ path: 'register', component: RegisterComponent },
{ path: 'login', component: LoginComponent}])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now, Create Auth Service-
D:\Angular\AngularMaterial>ng g service AuthService
create src/app/auth-service.service.spec.ts (405 bytes)
create src/app/auth-service.service.ts (117 bytes)
Auth Service looks like- auth-service.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class AuthServiceService {
constructor(private router: Router) { }
//Set User Secure Token
setSecureToken(secure_token: string) {
localStorage.setItem("LoggedIn", secure_token)
}
//Set User Secure Token
getSecureToken() {
return localStorage.getItem("LoggedIn")
}
//Check User is LoggedIn or not!
isLoggednIn() {
return this.getSecureToken() !== null;
}
//Logout method
logout() {
localStorage.removeItem("LoggedIn");
this.router.navigate(["login"]);
}
}
Now, calling the login service methods to validate user on login components and it looks like – login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthServiceService } from '../auth-service.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
//variable initialization
form;
//constructor initialization
constructor(private fbuilder: FormBuilder,
private route: Router,
private authService: AuthServiceService) {
this.form = fbuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required, Validators.minLength]
});
}
//ngOnInit method
ngOnInit() {
}
//This method use for Login
login() {
if (this.form.valid) {
this.authService.setSecureToken(this.form.value.email)
this.route.navigate(["dashboard"]);
}
}
}
Now, coming to your Auth Gourd and use your Auth service to validate the users and returns your status –
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){ }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(this.authService.isLoggednIn()){
return true;
}else{
this.route.navigate(["login"]);
return false;
}
}
}
You must add your Auth Service and Auth Guard in you app.module.ts and its looks like –
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule, FormGroup} from '@angular/forms';
import {RouterModule} from '@angular/router';
//MY COMPONENTS
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { AuthServiceService } from './auth-service.service';
import { AuthGuard } from './auth.guard';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{ path: '', component: AppComponent, pathMatch: 'full', canActivate: [AuthGuard] },
{ path: 'register', component: RegisterComponent },
{ path: 'login', component: LoginComponent}])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
0 comments:
Post a Comment