Skip to content

Commit

Permalink
Guarding the routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Popovkov57 committed Sep 28, 2022
1 parent 4ff93ac commit 501f9c9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,29 @@ import { StoreComponent } from './store/store.component';
import { CheckoutComponent } from './store/checkout.component';
import { CartDetailComponent } from './store/cartDetail.component';
import { RouterModule } from '@angular/router';
import { StoreFirstGuard } from './storeFirst.guard';

@NgModule({
imports: [BrowserModule, StoreModule,
RouterModule.forRoot([
{ path: "store", component: StoreComponent },
{ path: "cart", component: CartDetailComponent },
{ path: "checkout", component: CheckoutComponent },
{
path: "store", component: StoreComponent,
canActivate: [StoreFirstGuard]
},
{
path: "cart", component: CartDetailComponent,
canActivate: [StoreFirstGuard]
},
{
path: "checkout", component: CheckoutComponent,
canActivate: [StoreFirstGuard]
},
{ path: "**", redirectTo: "/store" }
])],
providers: [StoreFirstGuard],
declarations: [
AppComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
22 changes: 22 additions & 0 deletions src/app/storeFirst.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";
import { StoreComponent } from "./store/store.component";

@Injectable()
export class StoreFirstGuard {
private firstNavigation = true;

constructor(private router: Router) {}

canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (this.firstNavigation) {
this.firstNavigation = false;
if (route.component != StoreComponent) {
this.router.navigateByUrl("/");
return false;
}
}
return true;
}
}

0 comments on commit 501f9c9

Please sign in to comment.