import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
-import { Observable, of } from "rxjs";
+import { Observable } from "rxjs";
import { Chatroom } from "./chatroom";
+import { Message } from "./message";
@Injectable({
providedIn: 'root'
private uriList = 'http://localhost:8080/list';
private uriGet = 'http://localhost:8080/get/';
+ private uriListen = 'http://localhost:8080/listen/';
constructor(private http: HttpClient) { }
getChatroom(id: String): Observable<Chatroom> {
return this.http.get<Chatroom>(this.uriGet + id);
}
+
+ listen(id: String): Observable<Message> {
+ return new Observable<Message>((observer) => {
+ let url = this.uriListen + id;
+ let eventSource = new EventSource(url);
+ eventSource.onmessage = (event) => {
+ console.debug('Received event: ', event);
+ let message: Message = JSON.parse(event.data);
+ observer.next(message);
+ };
+ eventSource.onerror = (error) => {
+ // readyState === 0 (closed) means the remote source closed the connection,
+ // so we can safely treat it as a normal situation. Another way
+ // of detecting the end of the stream is to insert a special element
+ // in the stream of events, which the client can identify as the last one.
+ if(eventSource.readyState === 0) {
+ console.log('The stream has been closed by the server.');
+ eventSource.close();
+ observer.complete();
+ } else {
+ observer.error('EventSource error: ' + error);
+ }
+ }
+ });
+ }
}
-import { Component, OnInit } from '@angular/core';
+import { Component, OnInit, NgZone } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ChatroomService } from "../chatroom.service";
import { UserService } from "../user.service";
import { Chatroom } from "../chatroom";
+import { Message } from "../message";
@Component({
selector: 'app-chatroom',
export class ChatroomComponent implements OnInit {
chatroom: Chatroom = { id: 'FOO', name: 'BAR'};
+ messages: Message[] = [];
constructor(
private chatroomsService: ChatroomService,
private userService: UserService,
- private route: ActivatedRoute) {}
+ private route: ActivatedRoute,
+ private zone: NgZone) {}
ngOnInit(): void
{
this.chatroomsService
.getChatroom(id)
.subscribe(chatroom => this.chatroom = chatroom);
+ this.chatroomsService
+ .listen(id)
+ .subscribe({
+ next: message => this.zone.run(() => this.messages.push(message)),
+ error: err => console.error('something wrong occurred: ' + err) });
}
}
}