我试图用angular2动态加载一个组件,但它出现了以下错误:
异常:错误:未捕获(在承诺中):类型错误:无法读取未定义的属性“parentInjector”
这是代码:

@Component({
    selector: 'Notes5',
    template: `<span #extensionAnchor></span>`
 })

export class Notes5 extends NotesBase {
    constructor(private dynamicComponentLoader:DynamicComponentLoader, private NotesService:NotesService,
                protected sliderPanel:Sliderpanel,
                protected commBroker:CommBroker) {

        this.LoadComponentAsync("src/comps/app2/notes/NoteDynamic", "TestComponent", this.extensionAnchor);
    }

    @ViewChild('extensionAnchor', {read: ViewContainerRef}) extensionAnchor:ViewContainerRef;

    public LoadComponentAsync(componentPath:string, componentName:string, locationAnchor:ViewContainerRef) {
        System.import(componentPath)
            .then(fileContents => {
                console.log(fileContents);
                return fileContents[componentName]
            })
            .then(component => {
                this.dynamicComponentLoader.loadNextToLocation(component, locationAnchor)
            });
    }
}

有什么想法吗?
当做
肖恩

最佳答案

最初的错误是由于实际类名与尝试动态调用呈现的组件名不匹配造成的:即,如果引用的是TestComponent,则该类也必须命名为TestComponent
您当前的错误TypeError: Cannot read property 'parentInjector'是由于在呈现视图之前试图将内容加载到@ViewChild元素中导致的,因为您是在构造函数中调用它的。您需要在生命周期中进一步移动您的呼叫,例如ngAfterViewInit

constructor(private dynamicComponentLoader:DynamicComponentLoader,
            private NotesService:NotesService,
            protected sliderPanel:Sliderpanel,
            protected commBroker:CommBroker,
            private resolver: ComponentResolver) {
}

ngAfterViewInit() {
    this.LoadComponentAsync("src/comps/app2/notes/NoteDynamic",
        "TestComponent", this.extensionAnchor);
}

最后,由于DynamicComponentLoader已被弃用,您应该改用ComponentResolver
public LoadComponentAsync(componentPath:string, componentName:string,
                          locationAnchor:ViewContainerRef) {
    System.import(componentPath)
        .then(fileContents => {
            console.log(fileContents);
            return fileContents[componentName]
        })
        .then(component => {
            this.resolver.resolveComponent(component).then(factory => {
                locationAnchor.createComponent(factory, 0, locationAnchor.injector);
            });
        });
}

09-28 08:15