如何注入服务类,然后用其扩展的组成部分? [英] How to inject service to class and then extend component with it?

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

问题描述

我有类图层

 进口{AfterViewInit,ViewChild}从'angular2 /核心;
出口类层实现AfterViewInit {
  @ViewChild(元素)元素;  公共帆布:HTMLCanvasElement = NULL;
  公众环境:CanvasRenderingContext2D = NULL;  ngAfterViewInit(){
    this.canvas = this.element.nativeElement;
    this.context = this.canvas.getContext('2D');
  }
}

我会用我的组件将触角延伸

 进口{}组件从angular2 /核心;从./layer进口{}层;
进口{}游戏从'../../providers/Game';
@零件({
  选择:'行分量',
  模板:要求('./ template.html'),
  款式:[`
    帆布{
      的z-index:2;
    }
  `]
})
出口班线延伸层{
  构造函数(公共游戏:游戏){
    超();
  }
}

正如你所看到的,我有注入游戏服务于每一个组件,它将会从继承图层。不过,我想注入的服务图层类,这样我就可以使用它来创建依赖于服务方法,也不会强迫我注入服务在我自己的每一次的组件。

自不必说,注射服务图层,我会以任何部件无法正常工作。

我使用的角度2.0.0 beta.0


解决方案

构造函数添加到基类图层就像你在延伸类,并发送依赖如超级参数方法:

 出口类层实现AfterViewInit {
    构造函数(公共游戏:游戏){
        的console.log(游戏);
    }
}出口班线延伸层{
  构造函数(公共游戏:游戏){
    超(游戏);
  }
}

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

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

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