繁体   English   中英

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

[英]Cannot read property 'push' of undefined Typescript / Angular 6

我正在使用socket.io实现小型聊天应用程序,它运行良好。 但是我担心的是,当我进行新的聊天时,我需要将其分配给字符串数组以显示在列表视图中。

我只是简单地将数组定义为“消息:string [] = [];” 并在页面加载时推送示例字符串,它工作正常。但是当我从套接字收到新消息时, this.socket.on('newmessage',function(data) method将触发并可以读取新消息 。所有这些都正常工作。

但是,当我将新字符串放入“消息:string [] = [];”时 阵列。 我收到“无法读取未定义的属性“推””错误。

 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 }); } } 

this.messages.push(data.msg); //无法读取未定义的属性“ push”

因为你错了this 箭头函数可以解决该问题,例如,将this.socket.on('newmessage', function (data) {更改为this.socket.on('newmessage', (data) => {

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
    });

  }

}

我认为这是因为同步调用。我认为这不是标准方法,但是在我进行了这样的更改后它才起作用。

  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); }); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM