import { Injectable } from '@angular/core' ; import { Network } from '@ionic-native/network/ngx' ; import { Platform } from '@ionic/angular' ; import { DeviceService } from './device.service' ; import { BehaviorSubject } from 'rxjs' ; import { DataService } from './data.service' ; import { NoticeService } from './notice.service' ; @ Injectable ( { providedIn : 'root' } ) export class NetworkService { stateWatcher = new BehaviorSubject ( "unknow" ) ; connectSubscription ; watchNetworkTimer ; constructor ( private network , private platform , private deviceService , private dataService , private noticeService ) { } init ( ) { if ( ! this . platform . is ( 'cordova' ) ) return ; this . dataService . initCompleted . subscribe ( loaded => { if ( loaded ) { this . watch ( ) ; } } ) ; this . dataService . authDataExpire . subscribe ( state => { if ( state ) { this . unWatch ( ) ; } } ) ; } watch ( ) { this . connectSubscription = this . network . onConnect ( ) . subscribe ( ( ) => { window . clearTimeout ( this . watchNetworkTimer ) ; this . watchNetworkTimer = window . setTimeout ( ( ) => { if ( this . network . type != 'none' ) { this . deviceService . scanMdnsDevice ( ) ; this . stateWatcher . next ( this . network . type ) ; } } , 2900 ) ; } ) ; } unWatch ( ) { if ( typeof this . connectSubscription != 'undefined' ) this . connectSubscription . unsubscribe ( ) ; } }