javascript - 如何将服务注入(inject)到类中,然后用它扩展组件?

标签 javascript angular angular2-services

我有类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 服务注入(inject)到将从 Layer 继承的每个组件中。但是,我想将服务注入(inject)到 Layer 类中,这样我就可以使用它来创建依赖于服务的方法,而且它也不会强制我自己将服务注入(inject)到组件中每一次。

不用说,像我对任何组件那样向Layer注入(inject)服务是行不通的。

我正在使用 Angular 2.0.0-beta.0

最佳答案

将构造函数添加到基类 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);
  }
}

关于javascript - 如何将服务注入(inject)到类中,然后用它扩展组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34814263/

相关文章:

javascript - 如何理解错误 "TypeError: Cannot read property ' id' of undefined”?

angular - 找不到 '@angular/common/http' 模块

Angular2 注入(inject)的自定义服务未定义

javascript - 当我尝试使用 nodejs 请求模块传递 header 信息时,出现以下 TypeError 错误

javascript - JavaScript 中的原型(prototype)链返回未定义

javascript - 使用 mongodb 嵌入 Json 数据

javascript - 运行 ng build 时的 EPERM : operation not permitted, lstat

node.js - 在 node.js(和 Angular 2)上使用 systemjs

Angular 2 TypeScript如何在数组中查找元素

angular - 在angular2中使用订阅调用成功,错误回调?