2016-01-15 55 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

是的,我認爲如此;-) –

相關問題