来自数据库的 Angular 6 路由

Anuglar 6 Route From DataBase

我正在开发 angular 6 具有默认路由配置的应用程序, 我的问题是如何在用户登录后从数据库加载路由这就是我现在的路由。

const routes: Routes = [
  {
    path: "",
    redirectTo: "dashboard",
    pathMatch: "full"
  },

  {
    path: "services",
    data: { breadcrumb: "Services" },
    component: ServicesComponent,

  }]

和apireturn结果如下

{Path: "/Services", Component: "ServicesComponent"}
{Path: "/Dashboard", Component: "DashboardComponent"}

所以我如何用新值覆盖路由

提前致谢

您可以随时随地动态地将路由添加到您的 Router 实例。

您需要访问路由数组并添加一个新的,如下所示:

this.router.config.unshift({path: 'myNewRoute', component: ProductListComponent});

装饰器元数据解决方案

在您的情况下,您需要访问 Module 元数据,更准确地说是 Decorator 的声明,以搜索您需要的组件。您可以检查该组件的名称是否与 DB 收到的名称匹配。

let compName = 'ProductListComponent';
let comp: Type<any> = (<any>AppModule).__annotations__[0].declarations.find(comp => {
  return comp.name === compName;
});

this.router.config.unshift({path: 'myNewRoute', component: comp});

显然可以随意添加完整性检查。

映射解决方案

您可以像这样更简单地映射数据库字符串和组件:

let mapping = {
  'myNewRoute': ProductListComponent,
   ...
}

然后取消转移新路线如下:

this.router.config.unshift({path: 'myNewRoute', component: mapping['myNewRoute']});