src/app/services/chat.service.ts
Properties |
|
Methods |
|
constructor()
|
|
Defined in src/app/services/chat.service.ts:14
|
| Private Async createConnection |
createConnection()
|
|
Defined in src/app/services/chat.service.ts:26
|
|
Returns :
any
|
| Private registerOnServerEvents |
registerOnServerEvents()
|
|
Defined in src/app/services/chat.service.ts:47
|
|
Returns :
void
|
| sendMessage | ||||||
sendMessage(message: Message)
|
||||||
|
Defined in src/app/services/chat.service.ts:22
|
||||||
|
Parameters :
Returns :
void
|
| Private startConnection |
startConnection()
|
|
Defined in src/app/services/chat.service.ts:33
|
|
Returns :
void
|
| Private _hubConnection |
Type : HubConnection
|
|
Defined in src/app/services/chat.service.ts:14
|
| connectionEstablished |
Default value : new EventEmitter<Boolean>()
|
|
Defined in src/app/services/chat.service.ts:10
|
| Private connectionIsEstablished |
Default value : false
|
|
Defined in src/app/services/chat.service.ts:12
|
| messageReceived |
Default value : new EventEmitter<Message>()
|
|
Defined in src/app/services/chat.service.ts:8
|
import { EventEmitter, Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
import { Message } from '../models/message';
import { environment } from '../../environments/environment';
@Injectable()
export class ChatService {
messageReceived = new EventEmitter<Message>();
// tslint:disable-next-line: ban-types
connectionEstablished = new EventEmitter<Boolean>();
private connectionIsEstablished = false;
// tslint:disable-next-line: variable-name
private _hubConnection: HubConnection;
constructor() {
this.createConnection();
this.registerOnServerEvents();
this.startConnection();
}
sendMessage(message: Message) {
this._hubConnection.invoke('NewMessage', message);
}
private async createConnection() {
let connection = this._hubConnection = new HubConnectionBuilder()
.withUrl(environment.apiUrl + '/MessageHub')
.build();
await connection.start();
}
private startConnection(): void {
this._hubConnection
.start()
.then(() => {
this.connectionIsEstablished = true;
console.log('Hub connection started');
this.connectionEstablished.emit(true);
})
.catch(err => {
console.log('Error while establishing connection, retrying...');
setTimeout(function() { this.startConnection(); }, 5000);
});
}
private registerOnServerEvents(): void {
this._hubConnection.on('MessageReceived', (data: any) => {
this.messageReceived.emit(data);
});
}
}