Sunday, January 5, 2020

�� Angular route guards | Activate Route Guards in Angular 7 / 8 | Auth G...

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, Router} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router:Router)
{}

  canActivate(){

    if (localStorage.getItem('isLoggedin'))
    {
      return true;
    }

    this.router.navigate(['/login']);
    return false;
    
  }
  
}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
  {
    path:'', loadChildren:() => import ('./layout/layout.module').then(m=> m.LayoutModule),canActivate:[
      AuthGuard
    ]},
    {
      path:'login', loadChildren:() => import('./login/login.module').then(m=>m.LoginModule)
    }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts
import { BrowserModule} from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthGuard } from './auth.guard';

@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

layout.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LayoutComponent } from './layout.component';

const routes: Routes = [
  {
    path:'',
    component:LayoutComponent,
    children:[

      {
        path:'', redirectTo:'dashboard', pathMatch:'prefix'
      },
      {
        path:'dashboard', loadChildren:() => import('./dashboard/dashboard.module').then(m=>m.DashboardModule)

      }

    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

export class LayoutRoutingModule { }

layout.component.ts

<app-header></app-header>
<router-outlet></router-outlet>






1 comment:

  1. i write same code as you performed in video
    But I cant able to get access to login
    and also compiler didnt show any error

    ReplyDelete

Fetching JSON data from REST APIs

data.json---------------------------------- [     {     "userId" : 1 ,     "id" : 1 ,     "title" : "sunt...