Reputation: 17
I receive an object from socket, which I want to print to the screen using *ngFor. I get below error in console Error trying to diff 'asd'. Only arrays and iterables are allowed
angular ts
ngOnInit() {
console.log('ngOnInit');
this.socket.on('online',(people:number)=>{
console.log('online:',people);
})
this.socket.on('message',(data:any)=>{
console.log('socket-emit:',data);
})
this.socket.on('msg',(data:any)=>{
console.log(data);
this.MessageList = data;
for(let key in data){
this.MessageList.push(key);
}
// console.log(this.MessageList['name'] ,":",this.MessageList['message']);
})
}
angular html
<div *ngIf="MessageList">
<li *ngFor="let m of MessageList">
<span>{{m}}</span>
</li>
</div>
Upvotes: 0
Views: 569
Reputation: 267
When msg
socket is called, it passes only a single message object instead of whole array.
As such, you should not initialize your this.MessageList = data
as it will convert your MessageList
array to object, thereby making it non-iterable.
To get whole message list, you either have to:
Below is a snippet reflecting that;
this.socket.on('msg', (data:any) => {
console.log(data);
this.MessageList = data;
for(let key in data) {
this.MessageList.push(key);
}
// console.log(this.MessageList['name'], ":" , this.MessageList['message']);
});
Upvotes: 0
Reputation: 222522
Initialize your MessageList to empty array first
this.MessageList = [];
then as the error says ngFor supports only iterables such as arrays. so once you push the key it should work fine
Upvotes: 3