RxJS Socket.IO Angular Chat - Angular Component - Coding Blast - www.codingblast.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component, OnInit} from '@angular/core'; | |
import {ChatService} from '../chat.service'; | |
import * as moment from 'moment'; | |
import 'rxjs/add/operator/distinctUntilChanged'; | |
import 'rxjs/add/operator/filter'; | |
import 'rxjs/add/operator/skipWhile'; | |
import 'rxjs/add/operator/scan'; | |
import 'rxjs/add/operator/takeWhile'; | |
import 'rxjs/add/operator/throttleTime'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent implements OnInit { | |
message: string; | |
messages: string[] = []; | |
secretCode: string; | |
endConversationCode: string; | |
constructor(private chatService: ChatService) { | |
this.secretCode = 'DONT TELL'; | |
this.endConversationCode = 'BYE BYE'; | |
} | |
sendMessage() { | |
this.chatService.sendMessage(this.message); | |
this.message = ''; | |
} | |
ngOnInit() { | |
this.chatService | |
.getMessages() | |
.distinctUntilChanged() | |
.filter((message) => message.trim().length > 0) | |
.throttleTime(1000) | |
.takeWhile((message) => message !== this.endConversationCode) | |
.skipWhile((message) => message !== this.secretCode) | |
.scan((acc: string, message: string, index: number) => | |
`${message}(${index + 1})` | |
, 1) | |
.subscribe((message: string) => { | |
const currentTime = moment().format('hh:mm:ss a'); | |
const messageWithTimestamp = `${currentTime}: ${message}`; | |
this.messages.push(messageWithTimestamp); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment