【问题标题】:Component Inheritance and DI for base class resolver基类解析器的组件继承和 DI
【发布时间】:2018-09-14 01:06:25
【问题描述】:

我有不同类型的组件,但共享一些通用算法。所以我决定在 Angular 中使用组件继承并尝试使用模板方法模式。

基本上,我需要为某些方法做不同的实现。

基础组件

@Injectable()
export abstract class ComponentBase<IComponentViewData> {    
    public isReadOnly: boolean;
    public data: any;
    public message: string;

    // template method
    saveData(){
        validateBeforeSave();
        save();
        afterSave();
    }
    save(){
    }
    protected abstract afterSave(){
    }
    protected abstract validateBeforeSave(): void;

    }
    exit(){

    }
}

子组件 - A 型

@Component({
    templateUrl: "app/component/childA.component.html",
    selector: "child-a"

})
export class ChildAComponent extends ComponentBase<IChildTypeAViewData> { //IChildTypeAViewData : IComponentViewData

    protected afterSave(){
      this.message ='Child A executed successfully'
    }

}

ChildA.component.html

它使用父组件字段和方法。还嵌入了依赖于父组件的通用消息模板。

<div *ngIf="isReadOnly">
Show Data here
<button (click)="saveData()" />
<message></message>
</div>

在 ChildA.component 中嵌入消息组件

@Component({
    templateUrl: "app/common/message.html",
    selector: "message"

})
export class MessageComponent {

    constructor(@Host() hostComponent: ComponentBase<IComponentViewData>) {

    }
}

message.html

<div>{{ hostComponent.message }} </div>
<button (click)="exit()"></button>

问题:

当我在任何子类型中嵌入消息组件时,比如 ChildA, ChildB 我无法在 Message 中指定正确的派生类 组件@Host。所以依赖解析器提供了一个错误No provider for ComponentBase

我使用@Host 来访问包含的父组件的方法。它们中的大多数都在抽象组件中。

我们需要使用ComponentFactoryResolver吗?或者我们可以尝试其他方式来代替 Host?

【问题讨论】:

    标签: angular angular-components angular-di


    【解决方案1】:

    使用以下配置编辑ChildA.component.ts 元数据:

    @Component({
      templateUrl: "app/component/childA.component.html",
      selector: "child-a",
      providers: [
       { provide: ComponentBase, useExisting: forwardRef(() => ChildAComponent) }
      ]
    })
    

    父级必须通过以类接口令牌的名称为其自身提供别名来合作。

    更多信息在官方docs.

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 2015-05-14
      • 2018-03-14
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      相关资源
      最近更新 更多