问题
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){
}
}
what should i do to make this.list make defined?
回答1:
intialize your variable list to an empty array, otherwise it will be undefined when you try to push objects
private list: any[] = [];
also use arrow function and with this too.
this.socket.on('message', (data: any) => this.list.push(data.from + "
pressed Buzzer.");
来源:https://stackoverflow.com/questions/49749692/angular-4-error-typeerror-cannot-read-property-push-of-undefined