本文介绍了角度4-错误TypeError:无法读取未定义的属性'push'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的组件代码.我正在使用socket.on从节点服务器获取数据,然后将其推送到Typescript数组中.其在推送功能上显示错误.实际上,列表数组目前尚未定义.
this is my component code. and i am using socket.on to get data from node server and then want to push that into a Typescript array. its showing error on push function. actually list array is undefined at this point.
import { Component } from '@angular/core';
import * as io from 'socket.io-client';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent{
private socket: io.Socket;
private list: any[];
constructor() {
this.socket = io('wss://ngrk-buzzer-app.herokuapp.com');
this.socket.on('message', function (data) {
console.log(data);
this.list.push(data.from + " pressed Buzzer."); //this is where the error is
});
}
clearList(){
this.socket.emit("clear", "yes");
}
addItemInList(data){
}
}
我应该怎么做才能定义this.list?
what should i do to make this.list make defined?
推荐答案
将变量列表初始化为一个空数组,否则当您尝试推送对象时它将是未定义的
intialize your variable list to an empty array, otherwise it will be undefined when you try to push objects
private list: any[] = [];
也可以使用箭头功能.
this.socket.on('message', (data: any) => this.list.push(data.from + "
pressed Buzzer.");
这篇关于角度4-错误TypeError:无法读取未定义的属性'push'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!