【发布时间】:2016-06-23 13:27:09
【问题描述】:
我想从以 JSON 格式获取的服务中动态加载 @RouteConfig 的路由,
[
{ "path" : "/about" , "name" : "About" , "component" : "AboutComponent" },
{ "path" : "/contact" , "name" : "Contact" , "component" : "ContactComponent" }
]
以下是将其推入 RouteDefinition Array 的代码,
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}));
控制台错误:
路由“/about”的组件未定义,或者不是类。 我尝试了很多方法,比如使用
eval("new "+data[i].component+"()); || new window[data[i].component] .
我被困在这个问题上,对如何解决这个问题感到非常困惑。
【问题讨论】:
-
你试过
eval(data[i].component)吗?问题在于,除了在外部数据上使用eval()之外,它还需要该组件的import语句以及import {AboutComponent} from "path/to/component/about.component";。而且我不确定你怎么能做到这一点.. -
@PierreDuc 我确实有
import {AboutComponent} from './about/about.component';但是做var testClassName =eval(data[i].component);会导致错误AboutComponent 没有定义 -
好吧,试试
eval(data[i].component):) -
对不起@PierreDuc,但它导致了同样的事情,假设我做一个
var testClassName = new AboutComponent(); console.log(testClassName.constructor.name)正确输出到 AboutComponent 而不是以前不想要的版本 string -
啊,我明白为什么
eval不起作用了。如果您查看生成的js,您可以看到它导入了AboutComponent,可能类似于about_component_1.AboutComponent。因此,如果您可以将 camelCase 转换为下划线。全部小写,并添加_1。将该结果放入名为something的变量中。你可以做eval(something[data[i].component])。显然,编译后的 javascript 可能会发生变化,这可能是一个非常糟糕的方法,但您可以尝试 :D。虽然,编译器可能不会创建该变量,因为您并没有真正使用该组件
标签: angularjs routing typescript angular angular2-routing