TypeError:_co.class.function不是函数

时间:2018-05-15 10:09:45

标签: angular typescript

我正在学习Angular 6,我对它很陌生。
我的目标是定义一个类函数,然后从连接的组件中调用它,但是我得到以下错误。

TypeError: _co.installation.selectOrDeselect is not a function


installation.ts

export class Installation {
    id: number;
    name: string;
    img: string;
    version: number;
    agents: number;
    ip: string;
    connection: string;
    selection:  string;

    selectOrDeselect() {
        if (this.selection == 'not-selected') {
            this.selection = 'selected';
        } else {
            this.selection = 'not-selected';
        }
    }
}

installations.component.ts

import { Component, OnInit } from '@angular/core';
import { Installation } from '../installation';

@Component({
    selector: 'app-installations',
    templateUrl: './installations.component.html',
    styleUrls: ['./installations.component.css'],
})
export class InstallationsComponent implements OnInit {
    installation: Installation = {
        id: 1,
        name: 'Master',
        img: 'assets/logo.jpg',
        version: 7,
        agents: 95,
        ip: '192.168.0.1',
        connection: 'not-connected',
        selection: 'not-selected'
    };    

    constructor() { }

    ngOnInit() {

    }
}

installations.component.html

<div class=""class="col-2 installationContainer {{installation.selection}} {{ installation.connection  }}" (click)="installation.selectOrDeselect()">
    <h3>{{ installation.name }}</h3>
    <img src="{{ installation.img  }}">
    <div><label>versione: </label>{{ installation.version }}</div>
    <div><label>agenti: </label>{{ installation.agents  }}</div>
    <div><label>ip: </label>{{ installation.ip  }}</div>
</div>

1 个答案:

答案 0 :(得分:3)

installation: Installation = {...}

这里您只是通过typescript编译器指定编译时类型检查的对象类型。类型Installation将不会在运行时获取..只是您的对象。你需要这样做:

installation = new Installation();

让方法可用。 您可能还需要为Installation类定义一个构造函数,该构造函数接受所有属性并设置它。

export class Installation {

    constructor(
        public id: number;
        public name: string;
        public img: string;
        public version: number;
        public agents: number;
        public ip: string;
        public connection: string;
        public selection:  string;
    ){}

    selectOrDeselect() {
        if (this.selection == 'not-selected') {
            this.selection = 'selected';
        } else {
            this.selection = 'not-selected';
        }
    }
}

初始化:

installation = new Installation(1,'Master','assets/logo.jpg',7,95,'192.168.0.1','not-connected','not-selected');