首页 > 解决方案 > 将角度路由的路径提取到单独的文件中

问题描述

Angular 路由通常是这样定义和使用的:

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

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

我不想将路线移动到单独的文件 -我只想移动路径

所以我想提取"register""login"魔术字符串并将它们放在某个地方,然后这样做:

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

我有一个Configuration添加到 DI 的类,并在需要的地方注入它。如果可能的话,我想在那里添加路径。

一些选项:

  1. 我可以在该配置类上使用静态属性,但这是一个 hack 并且更难测试。
  2. 我可以像上面那样做const config = new Configuration();和使用它routes——但是如果它也需要成为 IOC 容器的一部分,因为它有自己的依赖项呢?
  3. 来自@DenisPupyrev 的回答:使用枚举。但与选项 2 一样,这意味着字符串必须在一个地方进行编码,而无需依赖(即没有 DI)。

所有这些都是不错的选择。但是提取魔术字符串并使用DI的最干净的方法是什么?

标签: angulartypescriptangular-routing

解决方案


在 TypeScript 中,您有很好的机会使用“枚举”。

路由.ts

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

应用程序路由.module.ts

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

升级版:

如果您需要 DI,您可以使用特殊服务:

路线服务.ts

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

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

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

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

任何.component.ts

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

推荐阅读