在Angular2中,使用继承还是注入依赖?

时间:2016-02-21 22:25:53

标签: angular typescript service

在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();
    }
}

1 个答案:

答案 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

DogImageenable都会从Base类继承currentImgonMouseOver()属性,onMouseClick()func_one(); func_two(); func_three(); // To be called as soon both of the above functions finish executing. 方法,您可以使用他们在他们的代码/模板中......