Angular 6调用类方法报错:TypeError: selectOrDeselect is not a function
解决Angular中“selectOrDeselect is not a function”的问题
嘿,我来帮你排查这个问题~你遇到的TypeError: _co.installation.selectOrDeselect is not a function错误,核心原因是你当前的installation并不是Installation类的实例,只是一个普通的对象字面量,所以类里定义的方法根本不存在于这个对象上。
问题根源
你在组件里是这么定义installation的:
installation: Installation = { id: 1, name: 'Master', // ...其他属性 };
这种写法是直接创建了一个普通JS对象,虽然它的属性和Installation类的属性一致,但它并没有继承Installation类的方法,本质上和Installation类没有关联,模板里调用selectOrDeselect()自然会报错。
解决方案:创建类的实例
要让对象拥有类里的方法,必须用new关键字创建Installation的实例,这里有两种方式:
方式1:给类添加构造函数,直接传参初始化
先修改你的installation.ts,添加一个构造函数,方便创建实例时直接赋值:
export class Installation { id: number; name: string; img: string; version: number; agents: number; ip: string; connection: string; selection: string; // 添加构造函数,接收属性参数 constructor( id: number, name: string, img: string, version: number, agents: number, ip: string, connection: string, selection: string ) { // 把参数赋值给类的属性 this.id = id; this.name = name; this.img = img; this.version = version; this.agents = agents; this.ip = ip; this.connection = connection; this.selection = selection; } selectOrDeselect() { if (this.selection === 'not-selected') { this.selection = 'selected'; } else { this.selection = 'not-selected'; } } }
然后在组件里用new创建实例:
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 { // 用new关键字创建Installation类的实例,传入属性值 installation: Installation = new Installation( 1, 'Master', 'assets/logo.jpg', 7, 95, '192.168.0.1', 'not-connected', 'not-selected' ); constructor() { } ngOnInit() { } }
方式2:先创建空实例,再逐个赋值
如果不想加构造函数,也可以先创建空的类实例,再在ngOnInit里给属性赋值:
// 组件里的代码 installation: Installation = new Installation(); ngOnInit() { this.installation.id = 1; this.installation.name = 'Master'; this.installation.img = 'assets/logo.jpg'; this.installation.version = 7; this.installation.agents = 95; this.installation.ip = '192.168.0.1'; this.installation.connection = 'not-connected'; this.installation.selection = 'not-selected'; }
额外小问题:模板里的语法错误
你的模板代码里有个小错误:class=""class="col-2..."这里多了一对引号,会导致样式失效,要改成:
<div 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>
这样修改后,你的selectOrDeselect()方法就能正常被调用啦~
内容的提问来源于stack exchange,提问作者user8794709
相关产品推荐
相关产品推荐

