在angular2中,假设我有一个Parent
类和一个Child1
类,它们具有相同的属性/成员和方法。如何初始化Child1
类?
服务
@Injectable()
export class Parent {
constructor(
private currentImg: string,
private catImg: string,
private dogImg: string,
private enable: boolean) {
}
onMouseOver() {
enable = true;
currentImg = catImg;
}
onMouseClick() {
enable = false;
currentImg = dogImg;
}
}
其中一个子类想要扩展Parent
类:
import {Parent} from "./Parent";
@Component({
selector: 'app',
templateUrl: 'app/child.html',
providers: [Parent]
})
export class Child1 {
private currentImg: string = "img/dog.png",
private catImg: string = "img/cat.png",
private dogImg: string = "img/dog.png",
private enable: false
constructor(private _parent: Parent) {
}
onMouseOver() {
this._parent.onMouseOver();
}
onMouseClick() {
this._parent.onMouseClick();
}
}
答案 0 :(得分:6)
扩展类主类时可以使用基类'方法和属性。
Base
如果要在主类中设置属性,则不要在基类中初始化/设置值。 您只需要声明在image
类中使用的属性和方法。您可以设置类将共享的公共属性,例如默认import {Base} from "./Base";
@Component({
selector: 'app',
template: `<button (click)="onMouseClick(image)">show cat</button>`,
providers: []
})
export class CatImage extends Base {
private image: string = "img/cat.png",
constructor() {
super();
}
}
@Component({
selector: 'app',
template: `<button (click)="onMouseClick(image)">show dog</button>`,
providers: []
})
export class DogImage extends Base {
private image: string = "img/dog.png",
constructor() {
super();
}
}
。< / p>
这是在两个不同的类中扩展Base类的方法:
CatImage
DogImage
和enable
都会从Base类继承currentImg
,onMouseOver()
属性,onMouseClick()
和func_one();
func_two();
func_three(); // To be called as soon both of the above functions finish executing.
方法,您可以使用他们在他们的代码/模板中......