Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "TypeError: ... is not a function" when trying to use a component function in template

I have a component as following and I am trying to provide my svg viewBox dimension dynamically, injected from my bootstrap in 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}`;
    }
}

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

And the exception I get

EXCEPTION: TypeError: l_context.getViewBox is not a function in [getViewBox() in AppComponent@1:13]

I'm not sure it's a good way to do this thing, but this information is needed elsewhere in my circles.service. One thing I don't like though is that I cannot specify the Number type so I have to define static parameters = [Circles, 'canvasWidth', 'canvasHeight']; in AppComponent.

like image 357
JCorriveau Avatar asked Oct 19 '22 14:10

JCorriveau


1 Answers

Remove function from your method declaration, It will look like below.

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

Basically what happen behind the scene is when you write class method with function, transpiled JavaScript throw that function outside of that prototype function returned by the name of class. That's why it become unreachable.

In this case you would have get error at compile, if you are using typescript with better tool like Visual Studio/Web Strom.

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

Transpiled As

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

Code Link

like image 175
Pankaj Parkar Avatar answered Oct 21 '22 06:10

Pankaj Parkar