我有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
服務將從Layer
繼承每個組件。然而,我想爲Layer
類注入服務,所以我可以使用它來創建依賴於服務的方法,並且它不會強制我每次都自己向組件注入服務。
不用說,注入服務Layer
,因爲我會對任何組件不起作用。
我使用的角度2.0.0 beta.0
那種我要傳遞的依賴作爲參數傳遞給'超()',但至少它在工作。 – Eggy