import { Injectable } from '@angular/core' ; import { ZilliqaService } from './zilliqa.service' ; import { Constants } from './constants' ; import * as $ from 'jquery' ; @ Injectable ( ) export class NetworkService { nodeConnected : boolean ; connectionAttempts : number ; nodeStatus : string ; networkBarVisible : boolean ; constructor ( private zilliqaService ) { this . nodeConnected = false ; this . connectionAttempts = 0 ; this . nodeStatus = 'Connected to network.' ; this . networkBarVisible = true ; } checkConnection ( ) { let that = this ; if ( ! ( navigator . onLine ) ) { this . failedConnection ( ) ; } this . zilliqaService . node . isConnected ( ( err , data ) => { if ( err ) { that . failedConnection ( ) ; } else { that . successfulConnection ( ) ; } } , ( err ) => { that . failedConnection ( ) ; } ) ; } successfulConnection ( ) { this . nodeConnected = true ; this . connectionAttempts = 0 ; this . nodeStatus = 'Connected to the network.' ; setTimeout ( ( ) => { this . networkBarVisible = false ; } , 3000 ) ; setTimeout ( ( ) => { this . checkConnection ( ) ; } , 15000 ) ; } failedConnection ( ) { this . nodeConnected = false ; this . networkBarVisible = true ; if ( this . connectionAttempts < Constants . MAX_CONNECTION_ATTEMPTS ) { this . nodeStatus = 'Connection attempt ' + this . connectionAttempts ++ + ' failed, retrying in ' + ( Constants . CONNECTION_ATTEMPT_TIMEOUT * this . connectionAttempts ) + 'ms' ; setTimeout ( ( ) => { this . checkConnection ( ) ; } , Constants . CONNECTION_ATTEMPT_TIMEOUT * this . connectionAttempts ) ; } else { this . nodeStatus = 'Connection failed ' + Constants . MAX_CONNECTION_ATTEMPTS + ' times. Please try again later.' ; } } }