![](/img/trans.png)
[英]Cannot read property 'push' of undefined Angular/Typescript
[英]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.