2

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

4

2 回答 2

2

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);
  }
}
于 2016-01-15T16:33:43.597 回答
0

我认为这是 Angular 不支持的。您需要在组件级别有一个构造函数来定义要注入的内容...

使用您的样本:

export class Layer {
  constructor(public game: Game) {
  }
}

@Component({
  (...)
})
export class Lines extends Layer {
  (...)
}

如果您查看Lines该类的转译文件,您会看到game参数存在于 Lines 构造函数中,而Game服务不存在于函数的第二个参数(组件的提供者列表)中__metadata

Lines = (function (_super) {
  __extends(Lines, _super);
  function Lines() { // <------------------
    _super.apply(this, arguments);
  }
  Lines = __decorate([
    core_1.Component({
      selector: 'lines-component',
      template: "\n    lines\n  ",
      styles: ["\n    canvas {\n      z-index: 2;\n    }\n  "]
    }), 
    __metadata('design:paramtypes', []) // <------------------
  ], Lines);
  return Lines;
})(app_layer_component_1.Layer);

而你constructor(public game: Game)Lines类中定义时拥有它:

Lines = (function (_super) {
  __extends(Lines, _super);
  function Lines(game) { // <------------------
    this.game = game;
  }
  Lines = __decorate([
    core_1.Component({
      selector: 'lines-component',
      template: "\n    lines\n  ",
      styles: ["\n    canvas {\n      z-index: 2;\n    }\n  "]
    }), 
    __metadata('design:paramtypes', [app_game_service_1.Game]) // <------------------
  ], Lines);
  return Lines;
})(app_layer_component_1.Layer);

希望它可以帮助你,蒂埃里

于 2016-01-15T16:44:22.030 回答