2016-03-05 66 views
2

我有一個組件,如下所示,我正在嘗試從main.ts中的bootstrap注入動態提供我的svg viewBox維度。嘗試在模板中使用組件函數時出現「TypeError:...不是函數」

import {Component} from 'angular2/core'; 
import {CircleComponent} from './circle.component'; 
import {Circles} from './circles.service'; 

@Component({ 
    selector: 'my-app', 
    styleUrls: ['./app/app.component.css'], 
    directives: [CircleComponent], 
    providers: [Circles],  
    template: ` 
     <svg [attr.viewBox]="getViewBox()" preserveAspectRatio="xMidYMid meet"> 
      <svg:g my-circle *ngFor="#circle of circles.circles" [circle]="circle" /> 
     </svg> 
    ` 
}) 
export class AppComponent{ 
    static parameters = [Circles, 'canvasWidth', 'canvasHeight']; 

    constructor(circles: Circles, canvasWidth: Number, canvasHeight: Number) { 
     this.circles = circles; 
     this.width = canvasWidth; 
     this.height = canvasHeight; 
    }  

    function getViewBox(): String { 
     return `0 0 ${this.width} ${this.height}`; 
    } 
} 

我main.ts

import {provide}  from 'angular2/core'; 
import {bootstrap}  from 'angular2/platform/browser' 
import {AppComponent} from './app.component' 

bootstrap(AppComponent, [ 
    provide('canvasWidth', {useValue: 900}), 
    provide('canvasHeight', {useValue: 300}) 
]); 

而例外,我得到

EXCEPTION: TypeError: l_context.getViewBox is not a function in [getViewBox() in [email protected]:13]

我不知道它是做這件事情的好辦法,但其他地方需要用到這些信息在我的circles.service中。我不喜歡的一件事是,我不能指定數字類型,所以我必須定義靜態參數= [Circles,'canvasWidth','canvasHeight']; AppComponent中的

回答

3

從您的方法聲明中刪除function,它將如下所示。

getViewBox(): String { 
    return `0 0 ${this.width} ${this.height}`; 
} 

基本上什麼發生在幕後是當你寫類方法與function,transpiled的JavaScript拋出function外通過類的名稱返回的原型功能。這就是爲什麼它變得無法訪問。

在這種情況下,如果您使用更好的工具(如Visual Studio/Web Strom)使用typescript,則編譯時會出錯。

export class App{ 
    function test(){ 
     console.log(); 
    } 
} 

Transpiled作爲

"use strict"; 
var App = (function() { 
    function App() { 
    } 
    return App; 
}()); 
exports.App = App; 
function test() { 
    console.log(); 
} 

Code Link

+0

哦,我還以爲是定義一個函數的方式,你是對的,它的工作,當我刪除它... – JCorriveau

+0

我有另一個類的另一個功能,如果我刪除功能的關鍵字,那一個是失敗的... – JCorriveau

+0

@JCorriveau你可以添加在你的問題失敗的代碼請 –

相關問題