Web
Analytics
Auth Guard in Angular 7 Login Example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Auth Guard in Angular 7 Login Example

In this example, I have taken a simple login example where a user may open dashboard after login only after successful login username will be stored into localstorage which is authentication for auth guard.

Take the Following steps :

  1. create two components login and dashboard.(ng g c /login/login, ng g c /dashboard/dashboard)
  2. Create a service “MyService” (ng g s MyService)
  3. Create a authguard(ng g g authguard)

Add Following code into service

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyServiceService {

  constructor() { }
  checkusernameandpassword(uname: string, pwd : string)
  {
if(uname == "admin" && pwd =="admin123"){
localStorage.setItem('username',"admin");
return true;
}
else{
  return false;
}
  }
}





Add Following code into authguard

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Routes, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private routes : Router){}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if(localStorage.getItem('username')!= null){
        return true;
          }
          else
          {
            this.routes.navigate(['/login']);
            return false;
          }
    
  }
}

Add Following code into login

import { Component, OnInit } from '@angular/core';
import { RouterModule , Router } from '@angular/router';
import { MyServiceService } from 'src/app/my-service.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [MyServiceService]
})
export class LoginComponent implements OnInit {

  constructor(private routes : Router, private service : MyServiceService) { }
msg="";
  ngOnInit() {
  }
  check(uname: string, p : string)
  {
    var output = this.service.checkusernameandpassword(uname, p);
    if(output == true)
    {
      this.routes.navigate(['/dashboard']);
    }
    else{
this.msg ='Invalid username or password';
    }


}
}

login.component.html

<p>
  login works!
</p>
<input type="text" #u1 /><br>
<input type="password" #p2 /><br/>
<button (click)="check(u1.value, p2.value)">Login</button>
<br/>
<span>{{ msg }}</span>





Write Following code into app.module.ts

import { AuthGuard } from './auth.guard';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard/dashboard.component';
import { LoginComponent } from './Login/login/login.component';
import { RouterModule, Routes } from '@angular/router';


const appRoutes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: "**", redirectTo: "/" }
];
@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    
    RouterModule.forRoot(appRoutes)
  ],
  
  providers: [AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }