Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject service to class and then extend component with it?

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

like image 488
Eggy Avatar asked Jan 29 '26 01:01

Eggy


1 Answers

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);
  }
}
like image 197
Langley Avatar answered Jan 30 '26 13:01

Langley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!