AJM
AJM

Reputation: 32490

Angular Routes - Avoiding Hardcoded Strings

I am a bit wary of having hardcoded route strings throughout my Angular app. It just seems a bit wrong! e.g.

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

Is there a way around this?

Upvotes: 8

Views: 1782

Answers (2)

Hristo Kolev
Hristo Kolev

Reputation: 1584

We had named routes but that concept died when Angular was in Beta(or was it RC).

You can do it with a global object with the routes as it's properties or you can do it with functions.

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

Upvotes: 2

nayakam
nayakam

Reputation: 4249

Define a static variable for router path in route module then use this through out the app. For example:

Define route path:

  export class AppRoutes {
        public static CUSTOMER: string = "customer";
        public static ERROR: string = "error";
    }

Route Config:

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

Navigation:

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

Upvotes: 5

Related Questions