Getting the messages

For both the general and the secret messages pages, we are going to be getting the same data. We are going to use RxJS to create an observable that wraps getting a single message back from the server as well as getting all currently sent messages back from the server.

Depending on the room string that's passed in, the GetMessages method joins either a secret room, just for logged in users, or the general room, available to all users. Having joined the room, we return an Observable instance where, on a particular event, we react. In the case of receiving the single message, we call the Observable instance's next method. This will be subscribed to by the client component, which will write this out. Similarly, we also subscribe on the socket to allMessages in order to receive all of the previously sent messages when we join the room. Again, we iterate over the messages and use next to write the message out.

My favorite part of this section is fromEvent. This is synonymous with the socket.on method of the userLogOn message and allows us to write out details about who logged in during the session:

public GetMessages = (room: string) => {
this.JoinRoom(room);
return Observable.create((ob) => {
this.socket.fromEvent<UserLogon>('userLogOn').subscribe((user:UserLogon) => {
ob.next(`${user.user} logged on at ${user.time}`);
});
this.socket.on('message', (msg:string) => {
ob.next(msg);
});
this.socket.on('allMessages', (msg:string[]) => {
msg.forEach((text:any) => ob.next(text.messageText));
});
});
}

Thus far, I have been fairly loose when using the terms messages and events to help with the flow of reading this chapter. In this instance, they both refer to the same thing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.93.221