This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
/
signalr.service.ts
70 lines (63 loc) · 2.33 KB
/
signalr.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { Injectable } from '@angular/core';
import { SecurityService } from './security.service';
import { ConfigurationService } from './configuration.service';
import { HubConnection, HubConnectionBuilder, LogLevel, HttpTransportType } from '@microsoft/signalr';
import { ToastrService } from 'ngx-toastr';
import { Subject } from 'rxjs';
@Injectable()
export class SignalrService {
private _hubConnection: HubConnection;
private SignalrHubUrl: string = '';
private msgSignalrSource = new Subject();
msgReceived$ = this.msgSignalrSource.asObservable();
constructor(
private securityService: SecurityService,
private configurationService: ConfigurationService, private toastr: ToastrService,
) {
if (this.configurationService.isReady) {
this.SignalrHubUrl = this.configurationService.serverSettings.signalrHubUrl;
this.init();
}
else {
this.configurationService.settingsLoaded$.subscribe(x => {
this.SignalrHubUrl = this.configurationService.serverSettings.signalrHubUrl;
this.init();
});
}
}
public stop() {
this._hubConnection.stop();
}
private init() {
if (this.securityService.IsAuthorized == true) {
this.register();
this.stablishConnection();
this.registerHandlers();
}
}
private register() {
this._hubConnection = new HubConnectionBuilder()
.withUrl(this.SignalrHubUrl + '/hub/notificationhub', {
accessTokenFactory: () => this.securityService.GetToken()
})
.configureLogging(LogLevel.Information)
.withAutomaticReconnect()
.build();
}
private stablishConnection() {
this._hubConnection.start()
.then(() => {
console.log('Hub connection started')
})
.catch(() => {
console.log('Error while establishing connection')
});
}
private registerHandlers() {
this._hubConnection.on('UpdatedOrderState', (msg) => {
console.log(`Order ${msg.orderId} updated to ${msg.status}`);
this.toastr.success('Updated to status: ' + msg.status, 'Order Id: ' + msg.orderId);
this.msgSignalrSource.next();
});
}
}