【问题标题】:Angular Routes - Avoiding Hardcoded StringsAngular Routes - 避免硬编码字符串
【发布时间】:2017-11-22 10:05:44
【问题描述】:

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

 this._router.navigate(['dashboard/customer', customer.CustomerId]);
path: 'customer',
component: CustomerComponent,

有没有办法解决这个问题?

【问题讨论】:

    标签: angular routing


    【解决方案1】:

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

    定义路由路径:

      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));
      

      【讨论】:

        猜你喜欢
        • 2016-07-14
        • 1970-01-01
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 2022-10-31
        • 1970-01-01
        相关资源
        最近更新 更多