FarmMapsLib/projects/common/src/fm/services/event.service.ts

63 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-04-15 19:31:02 +00:00
import { Injectable } from '@angular/core';
import { IEventMessage } from '../models/event.message';
2020-04-16 09:04:39 +00:00
import { Subject, timer } from 'rxjs';
2020-04-15 19:31:02 +00:00
import { OAuthService } from 'angular-oauth2-oidc';
import { HubConnection, HubConnectionBuilder, LogLevel ,HttpTransportType,HubConnectionState} from '@microsoft/signalr';
2020-04-15 19:31:02 +00:00
import { AppConfig } from "../shared/app.config";
@Injectable({
providedIn: 'root',
})
export class EventService {
public event:Subject <IEventMessage> = new Subject<IEventMessage>();
private _connection: HubConnection = null;
private _apiEndPoint: string;
2023-03-06 13:04:14 +00:00
public authenticated = false;
2020-04-15 19:31:02 +00:00
constructor(private oauthService: OAuthService, private appConfig: AppConfig) {
this._apiEndPoint = appConfig.getConfig("apiEndPoint");
this._connection = new HubConnectionBuilder().withUrl(`${ this._apiEndPoint}/eventHub`,
{ transport: HttpTransportType.WebSockets,
// accessTokenFactory: () => {
// return oauthService.getAccessToken();
// },
skipNegotiation:true
}).withAutomaticReconnect().configureLogging(LogLevel.Information).build();
this._connection.on('event', eventMessage => {
this.event.next(eventMessage);
});
this._connection.onreconnected( event => {
this.Authenticate();
});
this.Start();
}
Start() {
if(this._connection&&!(this._connection.state === HubConnectionState.Connected || this._connection.state === HubConnectionState.Connecting))
2020-04-15 19:31:02 +00:00
this._connection.start().then(() => {
this.Authenticate();
});
2020-04-15 19:31:02 +00:00
}
private Authenticate() {
2023-03-06 13:04:14 +00:00
const accessToken = this.oauthService.getAccessToken();
2020-09-30 16:30:36 +00:00
if (this.oauthService.hasValidAccessToken()) {
2020-04-15 19:31:02 +00:00
this._connection.send('authenticate', this.oauthService.getAccessToken());
2020-04-16 09:04:39 +00:00
this.authenticated=true;
} else {
//try again after half a second
setTimeout(() => {
this.Authenticate();
}, 800);
2020-04-15 19:31:02 +00:00
}
}
Stop() {
if(this._connection&&(this._connection.state === HubConnectionState.Connected || this._connection.state === HubConnectionState.Connecting)) {
this._connection.stop();
}
}
2020-04-15 19:31:02 +00:00
}