Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度2-使用字符串解析组件工厂_Angular_Typescript2.0 - Fatal编程技术网

Angular 角度2-使用字符串解析组件工厂

Angular 角度2-使用字符串解析组件工厂,angular,typescript2.0,Angular,Typescript2.0,这适用于Angular的2.1.0最终版本 我试图动态实例化一个组件,该组件的类型是从配置JSON文件传递的。我能找到的最好的东西是ComponentFactoryResolver,但是我找到的所有用法似乎都是将实际的Type对象传递给resolver 有没有办法从字符串中获取类型?因为目前,将类型作为字符串传递给我会出现以下错误: 未找到MyComponent的组件工厂 相关代码: StructureBuilder组件: private renderComponent(config:any)

这适用于Angular的2.1.0最终版本

我试图动态实例化一个组件,该组件的类型是从配置JSON文件传递的。我能找到的最好的东西是
ComponentFactoryResolver
,但是我找到的所有用法似乎都是将实际的
Type
对象传递给resolver

有没有办法从字符串中获取
类型
?因为目前,将类型作为字符串传递给我会出现以下错误:

未找到MyComponent的组件工厂

相关代码:

StructureBuilder组件:

private renderComponent(config:any) {
    let configComponents = config.components;
    if(config.hasOwnProperty('components') && configComponents.length){
        for(let i = 0, len = configComponents.length; i < len; i++){
            this.componentResolver.resolveComponentFactory(configComponents[i]);
        }
    }
}
就稀疏文档而言,这正是您应该做的

如果我将从
configComponents[I]
传入的动态字符串更改为
MyComponent
的实际导入类型引用,则它可以工作

因此,基本上,问题是:
有没有一种方法可以使用带字符串的
resolveComponentFactory
来解析组件,如果没有,有没有一种方法可以从字符串值获取
Type
引用?

我现在的解决方案是做我真正想避免的事情,那就是维护一个key/val注册表

let componentRegistry = {
    'SomeComp1': SomeComp1, 
    'SomeComp2': SomeComp2
}
然后用以下词语来称呼它:

private renderComponent(config:any) {
    let configComponents = config.components;
    if(config.hasOwnProperty('components') && configComponents.length){
        for(let i = 0, len = configComponents.length; i < len; i++){
            let comp = configComponents[i];
            this.componentResolver.resolveComponentFactory(this.componentRegistry[comp]);
        }
    }
}
private renderComponent(配置:any){
让configComponents=config.components;
if(config.hasOwnProperty('components')&&configComponents.length){
for(设i=0,len=configComponents.length;i
是否要将
'MyComponent'
作为字符串传递到
resolveComponentFactory
中?是的,很抱歉,这就是我的意思。请检查这个答案@yurzui。这个答案的问题是它使用了解析器的私有内部属性。像这样的私事会在未来的版本中发生变化,所以这不是一个可靠的解决方案。是的,你是对的。这样,您必须声明类似于
map={“MyComponent”:MyComponent}
的内容并使用它
private renderComponent(config:any) {
    let configComponents = config.components;
    if(config.hasOwnProperty('components') && configComponents.length){
        for(let i = 0, len = configComponents.length; i < len; i++){
            let comp = configComponents[i];
            this.componentResolver.resolveComponentFactory(this.componentRegistry[comp]);
        }
    }
}