How to convert a “String” value to “Type” in Angul

2020-03-02 05:33发布

问题:

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 structure:

"menu":[
        {
          "title":"Grid",
          "component":"GridPage"
        }
      ]

My Ts:

    this.menuService.getMenu().then((menu) => {
    this.menu = menu;
    });

    openPage(menu) {
      console.log("menu", menu.component);
      nav.setRoot(menu.component);
    }

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.

回答1:

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
}

and then just look the types up

class['Grid']

The disadvantage is that you need to know all supported classes in advance.



回答2:

I don't know Angular 2 in depth, but in a well structured application it is straightforward and feasible to get a Type using a string, if you know the fully qualified name of the given Type:

let typeName = "GridPage";
let ComponentType = MyApp.Components[typeName];

If you are getting the following type error:

Index signature of object type implicitly has an 'any' type.

... then you will need to type cast the preceding namespace (object). I prefer asserting to any in this case, as it's shorter than defining an inline interface for a string-based index signature, and you effectively don't lose any type-safety:

let ComponentType = (MyApp.Components as any)[typeName];

Additionally, this approach also works perfectly with modules:

import * as Components from "./components";

let ComponentType = (Components as any)[typeName];