gpt4 book ai didi

Angular 2 : trying to load a component dynamically, 获取:类型错误:无法读取属性 'parentInjector'

转载 作者:太空狗 更新时间:2023-10-29 18:26:45 25 4
gpt4 key购买 nike

我正在尝试使用 angular2 动态加载组件,但出现以下错误:

异常:错误:未捕获( promise ):TypeError:无法读取未定义的属性“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,则该类也必须命名为 测试组件

您当前的错误 TypeError: Cannot read property 'parentInjector' 是由于在呈现 View 之前尝试将内容加载到 @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);
});
});
}

关于 Angular 2 : trying to load a component dynamically, 获取:类型错误:无法读取属性 'parentInjector',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37578117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com