将组件注入其他组件会产生单例

时间:2017-12-18 13:19:22

标签: angular

以下是我的代码的一部分:

@Component({
    selector: '...',
    templateUrl: " "
})
export class QuoteComponent {
    address: boolean[] = [false, false];

    constructor() { }
     ...
}


import { QuoteComponent } from "...";
@Component({
    selector: '...',
    templateUrl: "...",
})
export class Addresses1Component {
    constructor(private quote: QuoteComponent) { }
}


import { QuoteComponent } from "...";
    @Component({
        selector: '...',
        templateUrl: "...",
    })
    export class Addresses2Component {
        constructor(private quote: QuoteComponent) { }
    }     

使用上述代码和而无需在任何地方定义提供商QuoteComponent是单身,Addresses1Component, Addresses2Component可以访问该代码。我希望行为像 services 而不是单身,因为我没有在providers数组中的某个地方定义它。对此有什么好的解释吗?

1 个答案:

答案 0 :(得分:0)

预计组件不可注射。使用反应式Forms API创建包含表单模板的共享组件。

如果您的QuoteComponent创建了一个应该在其他组件中可用的表单(带有表单数据),请创建一个服务,该服务将具有模仿表单模型属性的类型的变量myFormData。此外,在此服务中创建setter和getter:set formData()get formData()。此服务应注入QuoteComponent,Addresses1Component和Addresses2Component。

创建表单时,调用服务上的setter。在你的地址组件中,调用getter并使用setValue方法用来自服务的数据填充表单,例如:

this.myFormModel.setValue(myService.formData);