📘 Frontend Development - Routing in Angular

This section provides a detailed overview of the routing system used in the Angular-based frontend application. The routing system is defined in the app-routing.module.ts file and ensures navigation between various components while maintaining security and access control through route guards.


🛤️ Routing Configuration

The application's routes are structured in the app-routing.module.ts file. Below is an example of how routes are defined and guarded:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './_guards/auth.guard';
import { IsBrandGuard } from './_guards/isBrandGuard';
import { SidebarComponent } from './layout/sidebar/sidebar.component';
import { HomeComponent } from './components/home/home.component';
import { OrdersComponent } from './components/orders/orders.component';
import { PaymentsComponent } from './components/payments/payments.component';

const routes: Routes = [
  { path: 'add-tracking/:id', component: AddTrackingComponent },
  {
    path: '',
    component: SidebarComponent,
    canActivate: [AuthGuard],
    children: [
      { path: '', component: HomeComponent },
      { path: 'orders', component: OrdersComponent },
      { path: 'payments', component: PaymentsComponent },
    ],
  },
  {
    path: 'brands',
    component: SidebarComponent,
    canActivate: [AuthGuard, IsBrandGuard],
    children: [
      { path: '', component: BrandsComponent },
      { path: 'staff', component: StaffComponent },
    ],
  },
];

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

✨ Key Highlights:

  • Lazy Loading: Routes are grouped logically under parent components, improving performance.
  • Dynamic Parameters: Example: add-tracking/:id dynamically passes an ID to the component.

🔒 Route Guards

Angular route guards are used to control access to specific routes. The guards implemented in this project include:

1. AuthGuard

  • Purpose: Ensures only authenticated users can access certain routes.
  • Implementation:
    import { Injectable } from '@angular/core';
    import { CanActivate, Router } from '@angular/router';
    import { AccountsService } from '../services/accounts.service';
    
    @Injectable({ providedIn: 'root' })
    export class AuthGuard implements CanActivate {
      constructor(
        private router: Router,
        private accountsService: AccountsService
      ) {}
    
      canActivate(): boolean {
        const currentUser = this.accountsService.currentUserValue;
        if (currentUser) {
          return true;
        }
        this.router.navigate(['/login']);
        return false;
      }
    }
    
    • Redirects unauthenticated users to the /login page.
    • Checks user authentication via AccountsService.

2. IsBrandGuard

  • Purpose: Restricts access to routes meant for "Brand" users.
  • Implementation:
    import { Injectable } from '@angular/core';
    import { CanActivate, Router } from '@angular/router';
    import { AccountsService } from '../services/accounts.service';
    
    @Injectable({ providedIn: 'root' })
    export class IsBrandGuard implements CanActivate {
      constructor(
        private router: Router,
        private accountsService: AccountsService
      ) {}
    
      canActivate(): boolean {
        const currentUser = this.accountsService.currentUserValue;
        if (currentUser && currentUser.roleId >= 3) {
          return true;
        }
        this.router.navigate(['/']);
        return false;
      }
    }
    
    • Ensures only users with a roleId greater than or equal to 3 can access specific routes.
    • Redirects unauthorized users to the home page (/).

🗂️ Routing Structure

Route Component Guard Description
/add-tracking/:id AddTrackingComponent None Handles adding tracking information.
/ SidebarComponent AuthGuard Base route with child components.
/orders OrdersComponent AuthGuard Displays orders for authenticated users.
/payments PaymentsComponent AuthGuard Manages payment information.
/brands BrandsComponent AuthGuard, IsBrandGuard Restricted to brand-related users.
/brands/staff StaffComponent AuthGuard, IsBrandGuard Staff management for brand users.

🚀 How It Works

  1. Navigation: The RouterModule enables navigation between components based on the URL path.
  2. Guards: Guards like AuthGuard and IsBrandGuard restrict access to routes based on user roles or authentication status.
  3. Child Routes: Nested routes under SidebarComponent allow modular and reusable layouts.
  4. Dynamic Parameters: Routes like add-tracking/:id allow passing data directly in the URL.

🌟 Benefits

  • Security: Protects sensitive routes with guards.
  • Scalability: Modular route definitions make it easy to add new features.
  • User Experience: Dynamically loads components based on user roles, ensuring relevant content.

For more details, refer to the routing file: app-routing.module.ts【4:7†source】.