在Angular中添加动态路由?

huangapple go评论68阅读模式
英文:

Adding dynamic routes in angular?

问题

以下是已翻译的内容:

页面的路由信息以以下格式从API获取:

[{
    "name": "Contact",
    "url": "/customers/contact",
    "pages": [],
},
{
    "name": "Order",
    "url": "/customers/order",
    "pages": [
        {
            "name": "Stocks",
            "url": "/customers/order/stocks",
        },
        {
            "name": "Business",
            "url": "/customers/order/business",
        }
    ]
}]

在路由模块中将这些URL作为路径的最佳方法是什么?

硬编码URL没有意义,因为可能会添加新的语言,旧的URL路径可能会更新。

英文:

The routes for a page are coming from the API in the following format:

[{
    "name": "Contact",
    "url": "/customers/contact",
    "pages": [],
},
{
    "name": "Order",
    "url": "/customers/order",
    "pages": [
        {
            "name": "Stocks",
            "url": "/customers/order/stocks",
        },
        {
            "name": "Business",
            "url": "/customers/order/business",
        }
    ]
}]

What would be the best way to the the urls as paths in the routing module?

There's no point in hardcoding the urls as new languages will be added, the old ones might have updated paths.

答案1

得分: 0

Easiest: 使用通配符 alà

const routes: Routes = [
  { path: '**', component: DynamicComponent }
];

并让组件(在此情况下为 DynamicComponent)处理“路由”和加载视图作为示例。

其他方式,但有一点警告:
在 Router 中使用 resetConfig 方法。链接

constructor(private router: Router) {
  this.router.resetConfig(newRoutes);
}

使用这种方法,您可以创建全新的路由。但是(注意!)如果您更改此内容,将更改您的整个应用程序的所有路由。所以要小心!

英文:

Some ways:

Easiest: use wildcards alà

const routes: Routes = [
  { path: '**', component: DynamicComponent }
];

and let the component (DynamicComponent in this case) handle the "route" and loading the view as example.

Other way, but with little warning
The resetConfig method in Router. (Link)

constructor(private router: Router) {
  this.router.resetConfig(newRoutes);
}

With this you can create completely new routes. But (!!) if you change this you change all routes of you complete application. So be careful!

huangapple
  • 本文由 发表于 2023年5月11日 17:34:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定