I have class 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');
}
}
which I will be extending with my component 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();
}
}
As you can see, I have to inject Game service to every component which will inherit from Layer. However, I would like to inject service to Layer class, so I can use it to create methods which depends on the service, and also it won't force me to inject service to the component on my own every single time.
Needless to say, injecting service to Layer as I would to any component is not working.
I am using angular 2.0.0-beta.0
Add the constructor to the base class Layer just like you did on the extending class, and send the dependency as a parameter in the super method:
export class Layer implements AfterViewInit {
constructor(public game: Game) {
console.log(game);
}
}
export class Lines extends Layer {
constructor(public game: Game) {
super(game);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With