import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { Platform } from '@ionic/angular'; import { SignalRConnection } from './signalR'; import { Plugins } from '@capacitor/core'; const { App } = Plugins; @Injectable({ providedIn: 'root' }) export class SignalRService { private connection: SignalRConnection; private messageSubject: BehaviorSubject = new BehaviorSubject(null); private connectingSubject: BehaviorSubject = new BehaviorSubject(null); constructor( private platform: Platform,) { // this.startConnection(); // this.addMessageListener(); try { if (!this.platform.is('desktop')) { App.addListener('appStateChange', ({ isActive }) => { if (isActive) { // The app is in the foreground. console.log('App is in the foreground'); this.newConnection() } else { // The app is in the background. console.log('App is in the background'); // You can perform actions specific to the background state here. } }); } } catch(error) {} this.establishConnection() } private async establishConnection() { const connection = new SignalRConnection({url:'https://gdapi-dev.dyndns.info/stage/chathub'}) const attempConnection = await connection.establishConnection() if(attempConnection.isOk()) { this.connection?.closeConnection() this.connection = connection this.connection.getSendLater().subscribe(data => { }) this.connection.getMessages().subscribe((data) => { this.messageSubject.next(data) }) } } getMessage() { return this.messageSubject.asObservable() } async sendMessage(data: Object) { return await this.connection.sendMessage(data as any) } newConnection() { this.establishConnection() } }