我的circular dependency
服务出现@ComponentBuilderService
错误,因为我导入的某些组件,即BreakComponent
,LocationComponent
使用此服务并导入此@ComponentBuilderService
。
我要做的是使用此buildComponents()
中的@ComponentBuilderService
方法来动态创建组件,问题是某些组件需要使用此buildComponents()
在同一服务上构建子组件的方法。
@ComponentBuilderService:
@Injectable()
export class ComponentBuilderService {
private renderer: Renderer2;
constructor(private resolver: ComponentFactoryResolver, renderFactory: RendererFactory2) {
this.renderer = renderFactory.createRenderer(null, null);
}
buildComponents(nContainer: ViewContainerRef , elements) {
// loop through elements creating different components based on element.Type
elements.forEach((element, idx) => {
switch (element.Type) {
case 'break':
const breakComponent = nContainer.createComponent(this.resolver.resolveComponentFactory(BreakComponent));
console.log(breakComponent.location.nativeElement);
break;
case 'location':
const locationComponent = nContainer.createComponent(this.resolver.resolveComponentFactory(LocationComponent));
locationComponent.instance.Elements = element.Elements;
break;
}
});
}
}
@LocationComponent:
import { Component, AfterContentInit } from '@angular/core';
import { ComponentBuilder } from '../../../shared/services/component-build.service';
@Component({
selector: 'location',
template: `<div> some location building </div>`,
styleUrls: ['./location.component.scss'],
})
export class LocationComponent implements AfterContentInit {
Elements;
constructor(private componentBuilder: ComponentBuilder) { }
ngAfterContentInit() {
console.log(this.Elements);
this.componentBuilder.buildComponents(this.Elements);
}
}
问题:无论如何都要创建ComponentBuilderService
?