gpt4 book ai didi

angular - 如何在 Angular 中为路由参数指定类型

转载 作者:行者123 更新时间:2023-12-05 05:56:08 25 4
gpt4 key购买 nike

我在 Angular 模块中有以下路线


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 参数必须是整数

最佳答案

如果传递的参数是整数,您可以使用 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 },
];

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

关于angular - 如何在 Angular 中为路由参数指定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69280549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com