undefined未分配给ComponentFactory <any>&#39; DynamicComponent&#39;

时间:2017-08-21 16:01:24

标签: angular typescript

使用此directive

搜索MVC View in angle 2
export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
  const cmpClass = class DynamicComponent {};
  const decoratedCmp = Component(metadata)(cmpClass);

  @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
  class DynamicHtmlModule { }

  return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
    .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
      return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
    });
}

所有工作正常我的View呈现我想要的但几秒后这个错误弹出。

enter image description here

我的组件代码:

 import {
    Component,
    Directive,
    NgModule,
    Input,
    ViewContainerRef,
    Compiler,
    ComponentFactory,
    ModuleWithComponentFactories,
    ComponentRef,
    ReflectiveInjector, OnInit, OnDestroy, Type
} from '@angular/core';

import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {   
    const cmpClass = class DynamicComponent { };
    const decoratedCmp = Component(metadata)(cmpClass);

    @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
    class DynamicHtmlModule { }

    return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
        .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
            return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
        });
}

@Directive({ selector: 'mvc-partial' })
export class RenderingViewDynamic implements OnInit, OnDestroy {
    html: string = '<p></p>';
    @Input() url: string;
    cmpRef: ComponentRef<any>;

    constructor(private vcRef: ViewContainerRef, private compiler: Compiler, private http: Http) { }

    ngOnInit() {
        this.http.get(this.url)
            .map(res => res.text())
            .subscribe(
            (html) => {
                this.html = html;
                if (!html) return;

                if (this.cmpRef) {
                    this.cmpRef.destroy();
                }

                const compMetadata = new Component({
                    selector: 'dynamic-html',
                    template: this.html,
                });

                createComponentFactory(this.compiler, compMetadata)
                    .then(factory => {
                        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
                        this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
                    });
            },
            err => console.log(err),
            () => console.log('MvcPartial complete')
            );

    }

    ngOnDestroy() {
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
    }
}

我怎么能过来这个?

1 个答案:

答案 0 :(得分:0)

我认为问题在于您定义了一个返回Promise<ComponentFactory<any>>的方法,但是在方法中使用find函数可以返回undefined

  

find()方法返回数组中第一个元素的值   满足提供的测试功能。否则未定义是   返回。

这就是TS抱怨的。只需修改方法调用:

createComponentFactory(...): `Promise<ComponentFactory<any>> | Promise<undefined>` { ... }

同样的事情:

this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
                    });

createComponent只能ComponentFactory<C>,但在您的实施中,undefined可能会被传递。也许添加工厂存在的检查,或者如果你确定它永远不会被定义,请使用non-null断言操作符。