1+ import { Injectable } from '@angular/core' ;
2+ import { SecurityService } from './security.service' ;
3+ import { ConfigurationService } from './configuration.service' ;
4+ import { HubConnection , HttpConnection , TransportType } from '@aspnet/signalr' ;
5+ import { ToastsManager } from 'ng2-toastr/ng2-toastr' ;
6+ import { Subject } from 'rxjs' ;
7+
8+ @Injectable ( )
9+ export class SignalrService {
10+
11+ private _hubConnection : HubConnection ;
12+ private _httpConnection : HttpConnection ;
13+ private orderApiUrl : string = '' ;
14+ private msgSignalrSource = new Subject ( ) ;
15+ msgReceived$ = this . msgSignalrSource . asObservable ( ) ;
16+
17+ constructor (
18+ private securityService : SecurityService ,
19+ private configurationService : ConfigurationService , private toastr : ToastsManager ,
20+ ) {
21+ if ( this . configurationService . isReady ) {
22+ this . orderApiUrl = this . configurationService . serverSettings . purchaseUrl ;
23+ this . init ( ) ;
24+ }
25+ else {
26+ this . configurationService . settingsLoaded$ . subscribe ( x => {
27+ this . orderApiUrl = this . configurationService . serverSettings . purchaseUrl ;
28+ this . init ( ) ;
29+ } ) ;
30+ }
31+ }
32+
33+ public stop ( ) {
34+ this . _hubConnection . stop ( ) ;
35+ }
36+
37+ private init ( ) {
38+ if ( this . securityService . IsAuthorized == true ) {
39+ this . register ( ) ;
40+ this . stablishConnection ( ) ;
41+ this . registerHandlers ( ) ;
42+ }
43+ }
44+
45+ private register ( ) {
46+ this . _httpConnection = new HttpConnection ( this . orderApiUrl + '/orders-api/notificationhub' , {
47+ transport : TransportType . LongPolling ,
48+ accessTokenFactory : ( ) => this . securityService . GetToken ( )
49+ } ) ;
50+ this . _hubConnection = new HubConnection ( this . _httpConnection ) ;
51+ }
52+
53+ private stablishConnection ( ) {
54+ this . _hubConnection . start ( )
55+ . then ( ( ) => {
56+ console . log ( 'Hub connection started' )
57+ } )
58+ . catch ( ( ) => {
59+ console . log ( 'Error while establishing connection' )
60+ } ) ;
61+ }
62+
63+ private registerHandlers ( ) {
64+ this . _hubConnection . on ( 'UpdatedOrderState' , ( msg ) => {
65+ this . toastr . success ( 'Updated to status: ' + msg . status , 'Order Id: ' + msg . orderId ) ;
66+ this . msgSignalrSource . next ( ) ;
67+ } ) ;
68+ }
69+
70+ }
0 commit comments