也许有人知道如何动态构建路由(或者只是动态导入组件)。
例如:
我有 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/