动态构建路由{或动态组件导入} Angular 2

标签 dynamic import routes angular components

也许有人知道如何动态构建路由(或者只是动态导入组件)。

例如:

我有 JSON,其中包含带有 RouteName、路径、ComponentNames(字符串)的对象。 我想迭代它并动态构建路由定义(路由配置)。但我不知道如何动态导入组件。 我可以将字符串“ComponentName”从 JSON 传递到导入规则,因为导入需要静态定义(通过谷歌搜索在某些来源上找到了它)。

失败

let a = "MyComponentName"
import {a} from ......     

(我想到的一个想法 - 它 s like create some map key-value, and keep into key - route, value - Component, and after that equals routename from JSON and my MAP and push needed component into final route config array. But it 是如此丑陋的解决方案)也许存在另一种方式?

我卡住了。非常感谢您的帮助......

最佳答案

您可以利用Async 路由来执行此操作。根据您的路由配置,您可以从模块加载路由。在这种情况下,您需要添加模块路径以使组件与路由关联。

这是一个示例:

var routes = {
  path: '/path',
  name: 'some name',
  module: './my.component',
  component: 'MyComponentName'
}
routes.forEach((route : any) => {
  this.routeConfigArray.push(
      new AsyncRoute({
          path : route.path,
          loader : () => System.import(route.module).then(m => m[route.component]),
          name : route.name
      });
  );
});

this._router.config(this.routeConfigArray);

另一种方法可能是添加一个函数来获取函数的名称。在此基础上,您可以检查是否有匹配的潜在组件。

这是一个示例:

ngOnInit() {
  this.routes = [
    {
      path: '/test', component: 'OtherComponent', name: 'Test'
    }
  ];
  this.configureRoutes(this.routes);
  this.router.config( this.routes);
}

configureRoutes(routes) {
  var potentialComponents = [ OtherComponent ];
  routes.forEach((route) => {
    route.component = potentialComponents.find((component) => {
      return component.name === route.component;
    });
  });
}

查看这个plunkr:https://plnkr.co/edit/KKVagp?p=preview .

有关更多详细信息,请参阅此问题:

关于动态构建路由{或动态组件导入} Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36350906/

相关文章:

php - 如何在mysql中使用 'IN'创建动态查询

import - Google 日历 API - 导入事件 : Owner must be organizer or attendee

javascript - 为什么我不能在 Nodejs v10 中读取 "import * as readline from ' readline'"?

laravel - 将 'auth' 中间件与子域一起使用

php - Symfony 3 - 路由不包括特定路径的开头(url)

mysql - 在 cakephp 路由中使用 - 删除 url 的空白?

c - 访问C中的外部分配空间

java - Java 中的动态数组

c# - 如何将键值对列表转换为动态对象

objective-c - 包含文件时出错