如何将服务注入类,然后用它扩展组件? [英] How to inject service to class and then extend component with it?

查看:21
本文介绍了如何将服务注入类,然后用它扩展组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类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 扩展它:

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();
  }
}

如您所见,我必须向每个将从 Layer 继承的组件注入 Game 服务.但是,我想向 Layer 类注入服务,因此我可以使用它来创建依赖于服务的方法,并且它不会强迫我自己向组件注入服务每次.

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.

毋庸置疑,向 Layer 注入服务是行不通的.

Needless to say, injecting service to Layer as I would to any component is not working.

我使用的是 angular 2.0.0-beta.0

I am using angular 2.0.0-beta.0

推荐答案

将构造函数添加到基类 Layer 就像在扩展类中所做的一样,并将依赖项作为参数发送到基类 Layersuper 方法:

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);
  }
}

这篇关于如何将服务注入类,然后用它扩展组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆