Angular 4 - ERROR TypeError: Cannot read property 'push' of undefined

霸气de小男生 提交于 2020-01-30 10:57:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!