有没有办法在Angular 7中命名路线? [英] Is there a way to name a route in Angular 7?

查看:70
本文介绍了有没有办法在Angular 7中命名路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以在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中命名路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆