加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

从angular2中的字符串解析组件的类型<>

发布时间:2020-12-17 17:42:51 所属栏目:安全 来源:网络整理
导读:是否可以从字符串值获取组件类型(Type T)? Smth喜欢: let typeStr: string = 'MyComponent';let type: any = resolveType(typeStr); // actual type 解决方法 如果不为类保留“注册表”,则无法做到这一点. interface Component { }type ComponentClass = {
是否可以从字符串值获取组件类型(Type< T>)? Smth喜欢:

let typeStr: string = 'MyComponent';
let type: any = resolveType(typeStr); // actual type

解决方法

如果不为类保留“注册表”,则无法做到这一点.

interface Component { }

type ComponentClass = { new (): Component };

const REGISTRY = new Map<string,ComponentClass>();

function getTypeFor(name: string): ComponentClass {
    return REGISTRY.get(name);
}

至于如何向此REGISTRY添加条目,您有几个选项,这里有两个:

(1)在每个类定义后手动添加:

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
class ComponentA implements Component { ... }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读