尝试在模板中使用组件函数时出现错误“TypeError: ... is not a function”

JCo*_*eau 5 typescript angular

我有一个组件如下,我试图动态提供我的 svg viewBox 维度,从我的 bootstrap 注入到 main.ts。

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}`;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的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})
]);
Run Code Online (Sandbox Code Playgroud)

我得到的例外

例外:类型错误:l_context.getViewBox 不是 [getViewBox() in AppComponent@1:13] 中的函数

我不确定这是做这件事的好方法,但是我的 circles.service 的其他地方需要这些信息。我不喜欢的一件事是我不能指定 Number 类型,所以我必须定义静态参数 = [Circles, 'canvasWidth', 'canvasHeight']; 在 AppComponent 中。

Pan*_*kar 3

从方法声明中删除function,它将如下所示。

getViewBox(): String {
    return `0 0 ${this.width} ${this.height}`;
}
Run Code Online (Sandbox Code Playgroud)

基本上,幕后发生的事情是,当您使用 编写类方法时function,转译的 JavaScript 将其抛出function到类名称返回的原型函数之外。这就是为什么它变得无法访问。

在这种情况下,如果您使用typescriptVisual Studio/Web Strom 等更好的工具,则在编译时会出现错误。

export class App{
    function test(){
        console.log();
    }
}
Run Code Online (Sandbox Code Playgroud)

转译为

"use strict";
var App = (function () {
    function App() {
    }
    return App;
}());
exports.App = App;
function test() {
    console.log();
}
Run Code Online (Sandbox Code Playgroud)

代码链接