我有一种情况,根据所选的输入(收音机或复选框),我通过ajax动态添加一个组件。
Plunkr:https://plnkr.co/edit/uvGo3RxCkUPeuknVu9m8?p=preview
我解释了流程以便更好地理解:
第一层:src/parent/parent.ts
我们从questions.json获取json响应并填充问题。
根据controlType
,我们在a-component
中加载b-component
或src/parent/parent.html
。
当我选择a-component
中的复选框或b-component
中的单选按钮时,我拨打createDynamicComponent()
并传递componentData
。
componentData
只是基于所选选项需要填充的下一个组件的元数据信息。
现在,componentData
已从dynamic-component
或src/controls/a.html
src/controls/b.html
在dynamic-component
内,我解析了提供程序并将questions
数据注入entryComponents,(a-component
和b-component
)
一切正常,直到我在HService
和a-component
内引入b-component
(包含组件数据构建逻辑)。
我收到以下错误Error: Can't resolve all parameters for BComponent: ([object Object], [object Object], ?)
最后一个参数是HService
构造函数中的b-component
,如果我取出服务并使用注释代码,一切正常。
this.componentData = {
'questions': {
"question": "This is a " + this.level + " level question?",
"controlType": "radio",
"answers": [
"Yes",
"No",
"None"
]
},
"component": BComponent,
"level": this.level
};

编辑1:我已将HService
注入a-component
,并且没有提供商解决错误且工作正常。只有在将其添加到b-component
时,我才会遇到错误。
非常感谢帮助!!
答案 0 :(得分:3)
我认为问题是基于循环依赖。
A <=> HService
和B <=> HService
要解决这个问题,我会通过为HService
创建抽象类来释放依赖关系并将其用作令牌:
<强> base.h.ts 强>
export abstract class BaseHService {
private componentData: any;
abstract getComponentData(queries: IQ[], level: number): any;
}
<强> app.module.ts 强>
providers: [
{ provide: BaseHService, useClass: HService }, <== this line
{ provide: 'questions', useValue: {} },
{ provide: 'level', useValue: 1 }
],
<强> a.ts 强>
import { BaseHService } from "../h/base.h";
...
constructor(...private _h: BaseHService) {
<强> b.ts 强>
import { BaseHService } from "../h/base.h";
...
constructor(...private _h: BaseHService) {
<强> Modified Plunker 强>