2016-01-15 53 views
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

回答

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

那种我要传递的依赖作为参数传递给'超()',但至少它在工作。 – Eggy

0

我认为这是Angular不支持的东西。你需要有在组件水平的构造函数来定义要注入什么......

使用您的样本:

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

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

如果你看看transpiled文件的Lines类,你看到game参数存在于线构造函数和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); 

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

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

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

+0

有趣的是,也许注入是可能的,只有当类有一些装饰指定? – Eggy

+0

是的,我认为如此;-) –

相关问题