Angular 路由 - 避免硬编码字符串

8

我有点担心在我的Angular应用程序中到处使用硬编码的路由字符串。这似乎有点不对劲!例如:

 this._router.navigate(['dashboard/customer', customer.CustomerId]);
path: 'customer',
component: CustomerComponent,
有没有解决这个问题的方法?
2个回答

4
在路由模块中定义一个静态变量作为路由路径,然后在整个应用程序中使用它。例如:
定义路由路径:
  export class AppRoutes {
        public static CUSTOMER: string = "customer";
        public static ERROR: string = "error";
    }

路由配置:

const routes: Routes = [ 
  {
  path: AppRoutes.CUSTOMER, component: CustomerComponent
  }
];

导航:

this._router.navigate(["/" + AppRoutes.CUSTOMER, customer.CustomerId]);

2

我们曾经有过命名路由,但这个概念在 Angular 处于 Beta(或者 RC)版本时消失了。

你可以使用全局对象,并将路由作为它的属性来实现,或者你也可以使用函数来实现。

import { routes } from '../global-settings';

// with strings
this._router.navigate([routes.dashboard.customer, customer.CustomerId]);

// with functions
this._router.navigate(routes.dashboard.customer(customer.CustomerId));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接