我有类Layer
:
import {AfterViewInit, ViewChild} from 'angular2/core';
export class Layer implements AfterViewInit {
@ViewChild('element') element;
public canvas: HTMLCanvasElement = null;
public context: CanvasRenderingContext2D = null;
ngAfterViewInit() {
this.canvas = this.element.nativeElement;
this.context = this.canvas.getContext('2d');
}
}
我将使用我的组件 Lines
对其进行扩展:
import {Component} from 'angular2/core';
import {Layer} from './layer';
import {Game} from '../../providers/Game';
@Component({
selector: 'lines-component',
template: require('./template.html'),
styles: [`
canvas {
z-index: 2;
}
`]
})
export class Lines extends Layer {
constructor(public game: Game) {
super();
}
}
如您所见,我必须将 Game
服务注入(inject)到将从 Layer
继承的每个组件中。但是,我想将服务注入(inject)到 Layer 类中,这样我就可以使用它来创建依赖于服务的方法,而且它也不会强制我自己将服务注入(inject)到组件中每一次。
不用说,像我对任何组件那样向Layer
注入(inject)服务是行不通的。
我正在使用 Angular 2.0.0-beta.0
最佳答案
将构造函数添加到基类 Layer
中,就像在扩展类上所做的那样,并将依赖项作为 super
方法中的参数发送:
export class Layer implements AfterViewInit {
constructor(public game: Game) {
console.log(game);
}
}
export class Lines extends Layer {
constructor(public game: Game) {
super(game);
}
}
关于javascript - 如何将服务注入(inject)到类中,然后用它扩展组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34814263/