Is there a way to name a route in Angular 7?

孤街醉人 提交于 2019-12-23 07:31:13

问题


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?


回答1:


Considering you want to configure the routes names while you are creating the route configuration.

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" }}
]

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

Like in app.component.ts: (You don't need injection)

public routeNames = RouteNames;

Then the app.component.html will be something like:

<button [routerLink]="routeNames.routeNamesObject['Hello2']">Click to Navigate to Hello</button>



回答2:


<a [routerLink]="routerLinkVariable"></a>

So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below

export class myComponent {

     public routerLinkVariable = "/my/route/path"; // the value of the variable is string!
}



回答3:


In your class

public routeName = '/customRoute/myExample'

Then in your template

[routerLink]="routeName"

This should pull that value through, i think thats what you are asking for. This will only work if the customRoute is actually a valid route name you have made.




回答4:


You can use constant file for that so that it can be reusable in other components too.

export const ROUTE_URL = {
    myRouteName: '/my/route/path',
};

As many as you have.

then use that constant on .TS and use it in the view.

View:

<a [routerLink]="routerUrls.myRouteName"></a>

.TS:

public routerUrls= ROUTE_URL;

Even on your route file

 { path: 'xyz', loadChildren:  ROUTE_URL.myRouteName},


来源:https://stackoverflow.com/questions/53614857/is-there-a-way-to-name-a-route-in-angular-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!