[英]Using Angular's routes collection for populating a navigation area
When developing apps in Angular 2 I find myself having redundant code in my app when it comes to routes. 在Angular 2中开发应用程序时,我发现我的应用程序中有多余的代码。 Once I have my routes exported from a file for RouterModule use, I would imagine it to become a single source of truth - re-used for populating navigation areas in the app. 从文件导出路由以供RouterModule使用后,我可以想象它将成为事实的单一来源-重新用于填充应用程序中的导航区域。
The problem is, that the Route interface item does not allow any kind of 'label' attribute. 问题是, 路由接口项不允许任何类型的“标签”属性。 If it did, I could iterate over the array, pick up a specified level (root or children or any route) and if the path was not ''
or **
I would return the item and use its label
. 如果是这样,我可以遍历该数组,选择一个指定级别(根或子级或任何路由),如果路径不是''
或**
我将返回该项目并使用其label
。
Now, as wishful as it sounds, I just wanted to describe the problem. 现在,听起来很如意,我只想描述问题。 Has anyone come up to a sneaky solution for that purpose? 有人为此目的提出过偷偷摸摸的解决方案吗?
For a moment I thought of cloning the routes collection and applying my own labels on top of each item, but it would again produce some unnecessary code on another end 有一会儿,我想到克隆路由集合,并在每个项目的顶部添加我自己的标签,但这又会在另一端产生一些不必要的代码
The routes in an Angular application are just an array of objects. Angular应用程序中的路由只是对象的数组。 In other words, they're a JavaScript variable. 换句话说,它们是一个JavaScript变量。 How you obtain this variable is up to you. 如何获得此变量取决于您。
You could have an allRoutes
variable acting as the single source of truth: 您可以将allRoutes
变量用作事实的唯一来源:
// Note that I haven't used the `Routes` type.
// You could define your own interface for this.
const allRoutes: any[] = [
{ path: 'home', component: HomeComponent, label: 'Home' },
{ path: 'contact', component: ContactComponent, label: 'Contact' },
// ...
};
Then, use that to generate router-compatible routes: 然后,使用它来生成路由器兼容的路由:
// Iterate over `allRoutes` to produce the following.
// The `label` property is gone.
const routerFriendlyRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'contact', component: ContactComponent },
// ...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.