0

I am following this tutorial https://blog.briebug.com/blog/making-use-of-websockets-in-angular and it all works. However, the result is always [object Object] and I cannot figure out how to get the string value of what I sent displayed.

This is how the content is displayed:

<ul>
  <li *ngFor="let message of messages">{{ message }}</li>
</u>

and this is how the socket is used:

messages: Message[] = [];
destroyed$ = new Subject();

constructor(private webSocket: WebSocketService) {}

ngOnInit() {
  this.webSocket.connect().pipe(
    takeUntil(this.destroyed$)
  ).subscribe(messages => this.messages.push(messages));
}

sendMessage() {
  this.webSocket.send({ message: this.msgCtrl.value });
  this.msgCtrl.setValue('');
}

The tutorial uses the socket: wss://echo.websocket.org. So all it is doing is sending an 'echo' back of what I sent it. How can I display what it is sending back?

Ree
  • 863
  • 2
  • 18
  • 38
  • Try {{ message | json }} to see the shape of the message. My guess is you want {{ message.message }} – MikeOne Jun 25 '21 at 13:17
  • thank you! {{ message | json }} worked so I can finally see the result! but now how do I access that in ts so that I can do stuff with it?? – Ree Jun 25 '21 at 13:22
  • Depends on what you want to do with it :-) but you have access to it inside this.messages right? – MikeOne Jun 25 '21 at 13:25
  • Yeah. so my result is now displays something like { "message": "hello" } but what if I just want 'hello'... I am fairly new to angular. – Ree Jun 25 '21 at 14:13
  • {{ message.message }} should do the trick ;-) – MikeOne Jun 25 '21 at 14:21
  • Or you could do ngOnInit() { this.webSocket.connect().pipe( takeUntil(this.destroyed$) ).subscribe(messages => this.messages.push(messages.message)); } and then you can show just {{message}} – MikeOne Jun 25 '21 at 14:24
  • 1
    yayyy!! thank you!! – Ree Jun 25 '21 at 14:32
  • ;-) - enjoy coding - Angular rocks! – MikeOne Jun 25 '21 at 14:50

0 Answers0