2016-07-11 5 views
5

Мой вопрос является расширением другой вопрос здесь так: Angular2 and class inheritance supportугловой 2 унаследовать от базового компонента

А вот мой plunckr: http://plnkr.co/edit/ihdAJuUcyOj5Ze93BwIQ?p=preview

То, что я пытаюсь сделать, это следующее:

У меня есть общая функция, с которой все мои компоненты придется использовать. Как уже было сказано в вышеупомянутом вопросе, это можно сделать.

Мой вопрос: могу ли я иметь зависимости, введенные в базовый компонент? В моем plunkr заявленная зависимость (FormBuilder) не определена при входе в консоль.

import {AfterContentChecked, Component, ContentChildren, Input, QueryList, forwardRef, provide, Inject} from '@angular/core'; 
import { FormGroup, FormControl, Validators, FormBuilder, REACTIVE_FORM_DIRECTIVES } from '@angular/forms'; 



@Component({ 
    providers: [FormBuilder] 
}) 
export class BaseComponent { 
    // Interesting stuff here 
    @Input() id: string; 

    constructor(formBuilder: FormBuilder){ 
    console.log(formBuilder); 
    console.log('inside the constructor'); 
    } 


} 

@Component({ 
    selector: 'child-comp2', 
    template: '<div>child component #2 ({{id}})</div>', 
    providers: [provide(BaseComponent, { useExisting: forwardRef(() => ChildComponent2) })] 
}) 
export class ChildComponent2 extends BaseComponent { 


} 

@Component({ 
    selector: 'child-comp1', 
    template: '<div>child component #1 ({{id}})</div>', 
    providers: [provide(BaseComponent, { useExisting: forwardRef(() => ChildComponent1) })] 
}) 
export class ChildComponent1 extends BaseComponent { 


} 

@Component({ 
    selector: 'parent-comp', 
    template: `<div>Hello World</div> 
    <p>Number of Child Component 1 items: {{numComp1}} 
    <p>Number of Child Component 2 items: {{numComp2}} 
    <p>Number of Base Component items: {{numBase}} 
    <p><ng-content></ng-content> 
    <p>Base Components:</p> 
    <ul> 
    <li *ngFor="let c of contentBase">{{c.id}}</li> 
    </ul> 
    ` 
}) 
export class ParentComponent implements AfterContentChecked { 

    @ContentChildren(ChildComponent1) contentChild1: QueryList<ChildComponent1> 
    @ContentChildren(ChildComponent2) contentChild2: QueryList<ChildComponent2> 
    @ContentChildren(BaseComponent) contentBase: QueryList<BaseComponent> 
    public numComp1:number 
    public numComp2:number 
    public numBase:number 

    ngAfterContentChecked() { 
    this.numComp1 = this.contentChild1.length 
    this.numComp2 = this.contentChild2.length 
    this.numBase = this.contentBase.length 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: `<parent-comp> 
     <child-comp1 id="A"></child-comp1> 
     <child-comp1 id="B"></child-comp1> 
     <child-comp2 id="C"></child-comp2> 
    </parent-comp> 
    `, 
    directives: [ParentComponent, ChildComponent1, ChildComponent2] 
}) 
export class MyApplication { 

} 
+1

Нет, это не сработает, поскольку вы не можете наследовать аннотации базового класса. Но, возможно, этот ответ от Thierry Templier поможет вам обойти это: http://stackoverflow.com/a/36837482/1961059 – rinukkusu

ответ

7

Это не возможно, как вы делаете, так как Angular2 будет только взглянуть на аннотации к текущему компоненту, но не на компоненте выше.

Это, как говорится, вы можете работать на уровне аннотации сделать INHERIT аннотаций родительского компонента:

export function Inherit(annotation: any) { 
    return function (target: Function) { 
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor; 
    var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget); 

    Reflect.defineMetadata('design:paramtypes', parentAnnotations, target); 
    } 
} 

И использовать его как это:

@Inherit() 
@Component({ 
    (...) 
}) 
export class ChildComponent1 extends BaseComponent { 
    constructor() { 
    super(arguments); 
    } 
} 

Смотрите этот вопрос более детали:

Следующая статья может заинтересовать Вас, чтобы понять, что происходит под капотом:

Кроме того, необходимо иметь в виду, что работа над примечаниями непосредственно имеет свои недостатки, особенно в отношении автономного компиляции и для компонентная интроспекция в среде IDE.

+0

Где эта функция Inherit проживает? – Mastro

+1

, но как его можно скомпилировать TSC? 'super (arguments);' – slowkot

+0

Да, я также нашел 'super (arguments)', чтобы привести к ошибкам компиляции. – jcairney

Смежные вопросы