Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Routes - Avoiding Hardcoded Strings

Tags:

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?

like image 328
AJM Avatar asked Nov 22 '17 10:11

AJM


2 Answers

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]);
like image 181
nayakam Avatar answered Sep 20 '22 13:09

nayakam


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));
like image 27
Hristo Kolev Avatar answered Sep 21 '22 13:09

Hristo Kolev