Home > OS >  How to specity type for route parameter in Angular
How to specity type for route parameter in Angular

Time:09-23

I have the following routes in an angular module


const routes: Route[] = [
  {path: '', component: AdminProductsComponent, pathMatch: 'full'},
  {path: 'products', component: AdminProductsComponent, pathMatch: 'full'},
  { path: "products/:id", component: AdminProductDetailsComponent },
  { path: "products/:id/edit", component: EditProductComponent },
  { path: "orders", component: AdminOrdersComponent },
  { path: "orders/:id", component: AdminOrderDetailsComponent },
  { path: 'products/new', component: NewProductComponent },
];

But whenever I navigate to /products/new in the browser, AdminProductDetailsComponent gets loaded with the id param set to 'new'. How can I specify that the :id param in the 'products/:id' path must be an integer

CodePudding user response:

how about child routes? Did you try it?


const routes: Routes = [
    {
        path: 'products', component: AdminProductsComponent, pathMatch: 'full',
        children: [
           { path: 'new', component: NewProductComponent },
           { path: ":id", component: AdminProductDetailsComponent },
           { path: ":id/edit", component: EditProductComponent  },
        ]
    }
];

CodePudding user response:

You can check using canActivate for the route if the passed param is integer do your things else show an error message or re-route to proper path where you can feed correct information to the URL.

import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from "@angular/router";

export class TestService implements CanActivate {
    constructor(
    ){

    }

    canActivate(
      next: ActivatedRouteSnapshot,
      state: RouterStateSnapshot): boolean { 
           // here check the params
         const id =  next.paramMap.get('id') // we get it in string
         if (!isNan(id)) {
             return true;
         } else {
             // route it or do something you want
         }
      }

   
}

Add this guard to the route:


const routes: Route[] = [
  {path: '', component: AdminProductsComponent, pathMatch: 'full'},
  {path: 'products', component: AdminProductsComponent, pathMatch: 'full'},
  { path: "products/:id", component: AdminProductDetailsComponent, canActivate: [TestService] },
  { path: "products/:id/edit", component: EditProductComponent },
  { path: "orders", component: AdminOrdersComponent },
  { path: "orders/:id", component: AdminOrderDetailsComponent },
  { path: 'products/new', component: NewProductComponent },
];

There could be other ways too, open for suggestion how we could do it better.

  • Related