// ./guards/CanActivateViaAuth.guard.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
@Injectable()
export class CanActivateViaAuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate() {
// If the user is not logged in we'll send them back to the home page
try {
let logged = false;
// some check actions
// logged = result of checks
if (logged) {
return true;
} else {
//localStorage.clear();
console.log("notlogged");
this.router.navigate(["/"]);
}
} catch (ex) {
//localStorage.clear();
console.log("notlogged");
this.router.navigate(["/"]);
}
}
}
// app.module.ts
import { CanActivateViaAuthGuard } from "./guards/CanActivateViaAuth.guard";
/* other inports */
@NgModule({
declarations: [
/* app declarations */
],
imports: [
/* app imports */
],
providers: [
CanActivateViaAuthGuard,
/* other app providers */
],
bootstrap: [AppComponent],
})
export class AppModule {}
// app-routeing.module
import { CanActivateViaAuthGuard } from './guards/CanActivateViaAuth.guard';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [CanActivateViaAuthGuard],
}
];
@NgModule({
//{ enableTracing: true }
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}