Reputation: 21081
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:
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?All those are good options. But what is the cleanest way to extract the magic strings, and also use DI?
Upvotes: 2
Views: 973
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