【问题标题】:How to specity type for route parameter in Angular如何在Angular中指定路由参数的类型
【发布时间】:2021-09-22 08:17:36
【问题描述】:

我在一个角度模块中有以下路线


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 },
];

但是,每当我在浏览器中导航到 /products/new 时,AdminProductDetailsComponent 都会加载 id 参数设置为“new”。如何指定 'products/:id' 路径中的 :id 参数必须是整数

【问题讨论】:

  • 在 Angular 中,非参数化路由优先于参数化路由。

标签: angular routes


【解决方案1】:

子路由呢?你试过了吗?


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

【讨论】:

    【解决方案2】:

    如果传递的参数是整数,您可以使用 canActivate 检查路由,做其他事情显示错误消息或重新路由到正确的路径,您可以在其中向 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
             }
          }
    
       
    }
    

    将这个守卫添加到路由中:

    
    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 },
    ];
    
    

    也可能有其他方法,欢迎提出我们如何做得更好的建议。

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2023-03-04
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多