2016-03-14 30 views
1

我甚至不知道这是可能的打字稿,但我想从一个类继承的功能,如:打字稿功能继承

import {Component, AfterViewInit, ElementRef} from 'angular2/core'; 

@Component({}) 
class Class1 { 
    name: string; 
    constructor(private el: ElementRef) {} 

    private setName() { 
    this.name = "test"; 
    } 

    ngAfterViewInit() { 
    this.setName(); 
    } 
} 

@Component({ 
    selector: 'test' 
}) 
export class Class2 extends Class1 { 
    ngAfterViewInit() { 
    super.ngAfterViewInit(); 
    console.log(this.name); 
    } 
} 

,但我发现了以下错误在调用setName()函数时在控制台中:

EXCEPTION: TypeError: this.el is undefined

为什么不能正常工作?

+0

的的setName()函数居然是:'this.name = this.el.nativeElement.firstChild;' – danbsb

回答

0

构造函数没有被继承。你需要在每个子类

@Component({ 
    selector: 'test' 
}) 
export class Class2 extends Class1 { 
    constructor(el: ElementRef) { 
    super(el); 
    } 

    ngAfterViewInit() { 
    super.ngAfterViewInit(); 
    console.log(this.name); 
    } 
} 
0

考虑将el的范围更新为protected,这意味着它可以被声明的类和任何派生类访问。

// before 
constructor(private el: ElementRef) {} 

// after 
constructor(protected el: ElementRef) {} 
4

Constructors are not inherited.

他们来定义它们。下面的示例显示了这一点:

class Parent { 
    constructor(foo:number){} 
} 
class Child extends Parent {  
} 

const child1 = new Child(); // Error! 
const child2 = new Child(123); // OKAY! 

但这角

但是他们没有分析了依赖注入。这意味着你的子类的构造函数不会被调用与父类预期相同的参数(在你的情况下是`el)。您需要指定每个子类上的所有元素。所以偶然正确的代码是一个从接受的答案:

@Component({ 
    selector: 'test' 
}) 
export class Class2 extends Class1 { 
    constructor(el: ElementRef) { 
    super(el); 
    } 
}