gpt4 book ai didi

angularjs - Angular 2 中的动态路由加载失败。 (测试版)

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:59 24 4
gpt4 key购买 nike

我想从以 JSON 格式获取的服务动态加载 @RouteConfig 的路由,

[
{ "path" : "/about" , "name" : "About" , "component" : "AboutComponent" },
{ "path" : "/contact" , "name" : "Contact" , "component" : "ContactComponent" }
]

以下是将其插入 RouteDefinition 数组的代码,

for (let i = 0; i < data.length; i++) {
//console.log(data[i].path+" "+data[i].name+" "+data[i].component);
this.routeConfigArray.push({ //routeConfigArray : RouteDefinition
'path': data[i].path,
'name': data[i].name,
'component': data[i].component
});
this._router.config(this.routeConfigArray); // THIS FAILS TO CONFIG PATHS ON ROUTER
}

'component':data[i].component 需要 Classname,因为它通过 String 类接收它。如何将包含类名的字符串转换为类??

我也尝试过使用 Route 类:

this.routeConfigArray.push(new Route({path: data[i].path, name: data[i].name, component:data[i].component}));

控制台错误:

Component for route "/about" is not defined, or is not a class. i have tried numerous ways like using eval("new "+data[i].component+"()); || new window[data[i].component] .

我被困在这个问题上,对于如何解决这个问题真的很困惑。

最佳答案

TypeScript 以某种方式将导入编译为 javascript,您可以尝试类似这样的方法来使用 eval()(畏缩)。如果 typescript 的编译方式不同,这显然是行不通的,但是检查它是否能以任何方式工作很有趣 :)

for (let i = 0; i < data.length; i++) {
this.routeConfigArray.push({ //routeConfigArray : RouteDefinition
path: data[i].path,
name: data[i].name,
component: getComponent(data[i].component)
});
this._router.config(this.routeConfigArray);
}

function getComponent(comp : string) : Function {
//convert camelCase to underscore notation
let component : string = comp;
component = component[0].toLowerCase() + component.slice(1);
component = component.replace(/([A-Z])/g, function(match) {
return '_' + match.toLowerCase();
});
component += '_1';
return eval(component[comp])
}

附录

作为您自己使用 AsyncRoute 的解决方案的补充,我相信您实际上得到了一个非常好的解决方案。也许如果您以某种方式放置所有页面,您可以从 path 中提取 resource 位置,但这不是必需的。 (我的意思是从 path 字符串 /aboutresource 字符串 ./app/about/about.component 应该不难用一个小算法。但这可能需要更新。

无论如何,你可以用 AsyncRoute 尝试这样的事情

警告:前方未经测试的代码

let routes : any[] = [
{ "path" : "/about" , "name" : "About" , "component" : "AboutComponent", "route": "/About" , "resource" : "./app/about/about.component" },
{ "path" : "/contact" , "name" : "Contact" , "component" : "ContactComponent", "route": "/Contact" , "resource" : "./app/contact/contact.component" }
];

routes.forEach((route : any) => {
this.routeConfigArray.push(
new AsyncRoute({
path : route.path,
loader : () => System.import(route.resource).then(m => m[route.component]),
name : route.name
})
);
});

this._router.config(this.routeConfigArray);

关于angularjs - Angular 2 中的动态路由加载失败。 (测试版),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com