问题描述
我想知道是否有办法在 Angular7 中命名我的路由,这样我就可以调用 [routerLink]="myRouteName"
而不是 [routerLink]="/my/route/path"
.
I was wondering if there is a way to name my routes in Angular7 so I could just call [routerLink]="myRouteName"
instead of [routerLink]="/my/route/path"
.
如果是这样,我该如何实现?
If so, how can I achieve this?
推荐答案
考虑到您要在创建路由配置时配置路由名称.
Considering you want to configure the routes names while you are creating the route configuration.
让我们利用 routes'
数据属性为路由添加名称.(每条路线中的少量额外数据不应影响任何性能).
Lets leverage routes'
data property to add names to routes. (A small extra data in every route should not affect any performance).
但首先,让我们创建一个包含静态属性的类,用于保存路由名称及其实际路径.
But first, let's create a class which conatains a static property for holding route names and their actual paths.
export class RouteNames {
public static routeNamesObject = {}
}
现在在您定义路由的路由组件中,让我们像这样:
Now in your routing component where you have defined the routes, let's have it like:
const routes: Routes = [
{path: "hello/:id", component: HelloComponent, data: {routeName: "Hello1"}},
{path: "hello", component: HelloComponent, data: { routeName: "Hello2" }}
]
在这个变量初始化之后设置 RouteNames 类的静态属性
Just after this variable initialization set the RouteNames class's static prop
routes.forEach((eachRoute) => {
RouteNames.routeNamesObject[eachRoute.data.routeName] = eachRoute.path; // now all route paths are added to this prop
})
在你的组件中创建一个公共变量来访问静态类
Make a public variable in your component to access the static class
就像在 app.component.ts 中:(你不需要注入)
Like in app.component.ts: (You don't need injection)
public routeNames = RouteNames;
然后 app.component.html
将类似于:
<button [routerLink]="routeNames.routeNamesObject['Hello2']">Click to Navigate to Hello</button>
这篇关于有没有办法在 Angular 7 中命名路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!