解决类型来自angular2中的字符串的分量 [英] Resolve Type<> of component from string in angular2
本文介绍了解决类型来自angular2中的字符串的分量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以从string
值中获取组件(Type<T>
)的类型?像这样:
Is it possible to get type of component (Type<T>
) from string
value? Smth like:
let typeStr: string = 'MyComponent';
let type: any = resolveType(typeStr); // actual type
推荐答案
如果不为类维护注册表",您将无法做到这一点.
You can't do that without maintaining a "registry" for your classes.
interface Component { }
type ComponentClass = { new (): Component };
const REGISTRY = new Map<string, ComponentClass>();
function getTypeFor(name: string): ComponentClass {
return REGISTRY.get(name);
}
关于如何向此REGISTRY
添加条目,您有几个选择,有两个:
As for how to add entries to this REGISTRY
, you have a few options, here are two:
(1)在每个类定义之后手动添加它:
(1) Manually add it after every class definition:
class ComponentA implements Component { ... }
REGISTRY.set("ComponentA", ComponentA);
或者为其创建函数:
function register(cls: ComponentClass): void {
REGISTRY.set(cls.name, cls);
}
class ComponentA implements Component { ... }
register(ComponentA);
(2)使用装饰器:
只需将上述register
函数用作装饰器即可:
(2) Use a decorator:
Just use the above register
function as a decorator:
@register
class ComponentA implements Component { ... }
这篇关于解决类型来自angular2中的字符串的分量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文