首页 文章

无法读取未定义的Typescript / Angular 6属性'push'

提问于
浏览
0

我正在使用socket.io实现小型聊天应用程序,很高兴它工作正常 . 但我担心的是,当我进行新的聊天时,我需要将其分配给字符串数组以在listview中显示 .

我只是将数组定义为 "messages: string[] = [];" 并在页面加载时推送样本字符串并且它工作正常 . 但是当我从套接字获取新消息时 this.socket.on('newmessage', function (data) 方法将触发并且可以读取新消息 . 所有事情都正常工作 .

但是当我将新字符串推入我的 "messages: string[] = [];" 数组时 . 我'm getting '无法读取属性'push' of undefined'错误 .

import { Component, OnInit} from '@angular/core';
import * as io from 'socket.io-client';

@Component({
  selector: 'app-chatbox',
  templateUrl: './chatbox.component.html',
  styleUrls: ['./chatbox.component.css'],

})

export class ChatboxComponent implements OnInit {
  socket;
  messages: string[] = [];
  
  constructor() { this.socket = io.connect('http://localhost:8000'); }

  ngOnInit() {
    this.initializeChatServer();
  }

  initializeChatServer() {
  
    this.messages.push( 'test 55');//This line works

    this.socket.on('newmessage', function (data) {
      console.log('message -> ' + data.nick + '>' + data.msg);     
      this.messages.push(data.msg); //Cannot read property 'push' of undefined
    }); 
    
  }

}

3 回答

  • 0

    this.messages.push(data.msg); //无法读取undefined的属性'push'

    因为你错了 this . 箭头功能将解决这个问题 . 将 this.socket.on('newmessage', function (data) { 更改为 this.socket.on('newmessage', (data) => {

  • 0
    import { Component, OnInit} from '@angular/core';
    import * as io from 'socket.io-client';
    
    @Component({
      selector: 'app-chatbox',
      templateUrl: './chatbox.component.html',
      styleUrls: ['./chatbox.component.css'],
    })
    
    export class ChatboxComponent implements OnInit {
      socket;
      messages: string[] = [];
    
      constructor() { this.socket = io.connect('http://localhost:8000'); }
    
      ngOnInit() {
        this.initializeChatServer();
      }
    
      initializeChatServer() {
    
        this.messages.push( 'test 55');//This line works
    
        this.socket.on('newmessage', data => {
          console.log('message -> ' + data.nick + '>' + data.msg);     
          this.messages.push(data.msg); //Cannot read property 'push' of undefined
        });
    
      }
    
    }
    
  • 0

    我认为这是因为同步调用 . 我认为它不是标准的方式,但它在我改变之后起作用..

    initializeChatServer() {
    
        this.messages.push( 'test 55');
        var self = this;//assgin this to var variable
        this.socket.on('newmessage', data => {
          console.log('message -> ' + data.nick + '>' + data.msg);     
          self.messages.push(data.msg); 
        });
    
      }
    

相关问题