Angular Routes - 避免硬编码字符串

AJM*_*AJM 5 routing angular

我有点担心在我的 Angular 应用程序中使用硬编码的路由字符串。只是好像有点不对!例如

 this._router.navigate(['dashboard/customer', customer.CustomerId]);
Run Code Online (Sandbox Code Playgroud)
path: 'customer',
component: CustomerComponent,
Run Code Online (Sandbox Code Playgroud)

有没有解决的办法?

nay*_*kam 4

在路由模块中为路由器路径定义一个静态变量,然后在整个应用程序中使用它。例如:

定义路由路径:

  export class AppRoutes {
        public static CUSTOMER: string = "customer";
        public static ERROR: string = "error";
    }
Run Code Online (Sandbox Code Playgroud)

路线配置:

const routes: Routes = [ 
  {
  path: AppRoutes.CUSTOMER, component: CustomerComponent
  }
];
Run Code Online (Sandbox Code Playgroud)

导航:

this._router.navigate(["/" + AppRoutes.CUSTOMER, customer.CustomerId]);
Run Code Online (Sandbox Code Playgroud)