Make the file name ts auth.guard.ts enter the following code into
Enter security code
import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (localStorage.getItem('currentUser')) {
Add the following code to the ts routing file
application-routing.module.ts
{ path: 'user', component: UserComponent,canActivate: [AuthGuard] , children: [{ path: 'home', component: HomeComponent }, { path: 'view/:id', component: UserViewComponent }, { path: 'add', component: UserAddComponent }, { path: 'edit/:id', component: UserAddComponent } ] },
Add providers to the app.module.ts file
app.module.ts
@NgModule({ declarations: [ AppComponent -------- ], imports: [ BrowserModule -------- ], providers: [ AuthGuard ], bootstrap: [AppComponent] })
source share