如何转换“字符串"?“类型"的值在角 2 [英] How to convert a "String" value to "Type" in Angular 2

查看:19
本文介绍了如何转换“字符串"?“类型"的值在角 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 ionic 2 应用程序中创建一个侧边菜单,其中页面导航组件放置在借助 menuService.getMenu 函数获取的外部 json 文件中.

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.

我的 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 as Type(menu.component) 进行转换.但是我在控制台中的结果是一个匿名名称的函数.有人请帮助我将 json 字符串转换为组件类型"以便导航工作.

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.

这篇关于如何转换“字符串"?“类型"的值在角 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆