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;
}
}
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>
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 { }
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 { }
<app-header></app-header>
<router-outlet></router-outlet>
i write same code as you performed in video
ReplyDeleteBut I cant able to get access to login
and also compiler didnt show any error