如何转换“字符串”值为“类型”在Angular 2中 [英] How to convert a "String" value to "Type" in Angular 2
问题描述
我想在ionic 2应用程序中创建一个侧面菜单,其中页面导航组件放在一个外部json文件中,该文件是在menuService.getMenu函数的帮助下获取的。
I want to create a side menu in ionic 2 application where the page navigation component is placed in a external json file fetched with the help of menuService.getMenu function.
MY JSON结构:
MY JSON structure:
"menu":[
{
"title":"Grid",
"component":"GridPage"
}
]
我的Ts:
this.menuService.getMenu().then((menu) => {
this.menu = menu;
});
openPage(menu) {
console.log("menu", menu.component);
nav.setRoot(menu.component);
}
控制台日志打印字符串GridPage。我尝试使用Type作为Type(menu.component)进行转换。但我在控制台中的结果是一个具有匿名名称的函数。有人请帮助我将json字符串转换为组件Type以便导航工作。
Console log prints the string GridPage. I tried to convert using Type as Type(menu.component). But my result in console is a function with anonymous name. Someone please help me on getting the json string converted to component "Type" for navigation to work.
推荐答案
我想有一种方法可以通过字符串获取类的类型,但我不知道(我不知道)使用TS)。一个简单的解决方法是
I guess there is a way to get the type of a class by string but I don't know (I don't use TS). A simple workaround would be to
创建一个从字符串到类型的地图
create a map from string to type
classes = {
'MyClass1': MyClass1,
'MyClass2': MyClass2,
'Grid': Grid
}
然后查看类型
class['Grid']
缺点是您需要提前知道所有支持的类。
The disadvantage is that you need to know all supported classes in advance.
这篇关于如何转换“字符串”值为“类型”在Angular 2中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!