我有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