lonix
lonix

Reputation: 21081

Extract angular routing's paths into separate file

Angular routes are typically defined and used like this:

const routes: Routes = [
  { path: "register", component: RegisterComponent },
  { path: "login", component: LoginComponent },
  // more...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export default class AppRoutingModule { }

I don't want to move the routes to a separate file - I want to move the paths only.

So I want to extract the "register" and "login" magic strings and put them somewhere, and then do this:

const routes: Routes = [
  { path: config.routes.register, component: RegisterComponent },
  { path: config.routes.login, component: LoginComponent },
  // more...
];

I have a Configuration class I added to DI, and I inject it wherever I need it. I want to add the paths there, if possible.

Some options:

  1. I could use static properties on that config class, but that is a hack and harder to test.
  2. I could do const config = new Configuration(); and use it in routes like above - but what if it also needs to be part of the IOC container as it has its own dependencies?
  3. From @DenisPupyrev's answer: use enums. But like option 2, this means the strings must be encoded in one place without needing dependencies (i.e. no DI).

All those are good options. But what is the cleanest way to extract the magic strings, and also use DI?

Upvotes: 2

Views: 973

Answers (1)

Denis Pupyrev
Denis Pupyrev

Reputation: 76

In TypeScript you have a great opportunity to use "Enums".

Routes.ts

export enum Routes {
  LOGIN = 'login',
  REGISTER = 'register',
  ...
}

app-routing.module.ts

import { Routes } from './path/to/Routes';
...
{ path: Routes.LOGIN, component: LoginComponent }

UPD:

If you need DI, you can use special service:

route.service.ts

@Injectable()
export class RouteService {
  routes = {};

  constructor() {
    this.addRoute('login');
  }

  addRoute(route: string) {
    this.routes[route] = route;
  }

  get ROUTES() {
    return this.routes;
  }
}

any.component.ts

import { RouteService } from './path/to/route.service';
...
constructor(private routeService: RouteService) {}
...
anyMethod() {
  this.routeService.ROUTES.login;
}

Upvotes: 3

Related Questions