Angular2 - 注入循环引用的动态组件时,依赖注入不起作用

时间:2017-04-04 04:14:02

标签: javascript angularjs angular

我有一种情况,根据所选的输入(收音机或复选框),我通过ajax动态添加一个组件。

Plunkr:https://plnkr.co/edit/uvGo3RxCkUPeuknVu9m8?p=preview

我解释了流程以便更好地理解:

第一层:src/parent/parent.ts

我们从questions.json获取json响应并填充问题。

根据controlType,我们在a-component中加载b-componentsrc/parent/parent.html

当我选择a-component中的复选框或b-component中的单选按钮时,我拨打createDynamicComponent()并传递componentData

componentData只是基于所选选项需要填充的下一个组件的元数据信息。

现在,componentData已从dynamic-componentsrc/controls/a.html

传递到src/controls/b.html

dynamic-component内,我解析了提供程序并将questions数据注入entryComponents,(a-componentb-component

一切正常,直到我在HServicea-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时,我才会遇到错误。

非常感谢帮助!!

1 个答案:

答案 0 :(得分:3)

我认为问题是基于循环依赖。

A <=> HServiceB <=> 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