Anuglar 6 数据库路线

问题描述 投票:0回答:1

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

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

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

  }]

API 返回以下结果

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

那么我如何用新值覆盖路线

提前致谢

angular6
1个回答
0
投票

您可以随时随地动态添加路由到您的

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']});
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.