0

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 Answer 1

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."); 
Sign up to request clarification or add additional context in comments.

3 Comments

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."); }); }
use arrow function
As sajeetharan Said: use the Arrow function. Otherwise 'this' is not what you expect inside the CB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.