How to handle net::ERR_CONNECTION_REFUSED in Ionic 6

At the time of login if my server is not connected.
How to handle errors as follows:

GET http://192.168.2.190:3000/api/ckdDetails/getAppVersion/A net::ERR_CONNECTION_REFUSED.

I need to tell the user by alert that the API server hasn’t started. How should I handle the error?

below is my “Login.page.ts”

import { HttpClient } from ‘@angular/common/http’;
import { Component, Input, OnInit } from ‘@angular/core’;
import { FormBuilder, FormGroup, NgForm, Validators } from ‘@angular/forms’;
import { Router, NavigationExtras } from ‘@angular/router’;
import { SQLite, SQLiteObject } from ‘@ionic-native/sqlite/ngx’;
import { File } from ‘@ionic-native/file/ngx’;
import { AlertController, IonRouterOutlet, MenuController, Platform } from ‘@ionic/angular’;
import { LoginService } from ‘./login.service’;
// import SecureRNG from ‘secure-rng’;
import { Storage } from ‘@ionic/storage’;
import { LoadingController } from ‘@ionic/angular’;
import { ScreenOrientation } from ‘@ionic-native/screen-orientation/ngx’;
import { isPlatformBrowser } from ‘@angular/common’;
import {AppVersion} from ‘@ionic-native/app-version/ngx’;
// import { version } from ‘process’;
import { InAppBrowser } from ‘@awesome-cordova-plugins/in-app-browser/ngx’;
import { ConnectionStatus, ThemesService } from ‘…/service/themes.service’;
import { Network } from ‘@ionic-native/network/ngx’;

// import { Server } from ‘http’;

@Component({
selector: ‘app-login’,
templateUrl: ‘./login.page.html’,
styleUrls: [‘./login.page.scss’],
})
export class LoginPage implements OnInit {

userForm: FormGroup;
private database: SQLiteObject;
formObj: {}
ID: string;
loading: any;
DOB: any;

protected app_version: string;

@Input() name: string;

constructor(private router: Router,
private sqlite: SQLite, private http: HttpClient,
private fb: FormBuilder,
private file: File,
private loginservice: LoginService,
private alertController: AlertController,
public storage: Storage,
private loadingController: LoadingController,
private platform: Platform,
private screenOrientation: ScreenOrientation,
private appVersion: AppVersion,private iab: InAppBrowser,
private themesService: ThemesService,
public menuCtrl: MenuController,
// private routerOutlet: IonRouterOutlet,
// private connectivity: ThemesService,private network: Network
) {

this.initializeApp();

this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);


this.userForm = this.fb.group({
  username: ['', [Validators.required]],
  password: ['', [Validators.required]],
})
 }

model = {
username: ‘’,
password: ‘’
};
passRegExp = /^(?=.?[A-Z])(?=.?[a-z])(?=.*?[0-9]).{8,}$/;

ngOnInit() {

// this.routerOutlet.swipeGesture = false;

// this.loading.present();

if (this.platform.is('android') || this.platform.is('ios')) {
this.createTables(); // Create all tables 

}
//this.enableDarkTheme();

}

ionViewWillEnter() {
this.menuCtrl.enable(false);
}

// ionViewDidLeave() {
// // enable the root left menuCtrl when leaving the tutorial page
// this.menuCtrl.enable(true);
// }

createTables() {
this.sqlite.create({
name: ‘ckdManagment.db’,
location: ‘default’
}).then((db: SQLiteObject) => {
db.executeSql(‘CREATE TABLE USERINFO (ID TEXT,PASSWORD TEXT,PASSWORD_CHANGE_DATE TEXT,FIRST_NAME TEXT,MIDDLE_NAME TEXT,LAST_NAME TEXT,EMAIL TEXT,MOBILE_NUMBER TEXT,GENDER TEXT,DOB TEXT,LINE1 TEXT,LINE2 TEXT,LINE3 TEXT,CITY TEXT,PIN_CODE TEXT,LOCK_STATUS TEXT,DEVICE_ID TEXT,MOB_DEVICE_ID TEXT,SID TEXT,ISACTIVE TEXT,FIRST_TIME_RECORD_FLG TEXT,TEMP_PWD_FLG TEXT,TEMP_PWD_ISSUE_DT TEXT,ACCOUNT_EXPIRY_FLG TEXT,TERMINATION_FLG TEXT,ACCOUNT_LOCK_FLG TEXT,EMAIL_SMS_SENT_FLG TEXT,NO_OF_ATTEMPTS TEXT,LAST_LOGIN_DT TEXT,AGENT_CODE TEXT,COUNTRY_CODE TEXT)’)
.then(res => console.log(‘Executed SQL’))
.catch(e => console.log(e));

  this.sqlite.create({
    name: 'ckdManagment.db',
    location: 'default'
  }).then((db: SQLiteObject) => {
    db.executeSql('CREATE TABLE AL_USER_REPORT_DETAILS (USER_ID  TEXT,REPORT_ID TEXT,REPORT_ENTRY_TYPE  TEXT,REPORT_TEST_VALUES TEXT, DIAGNOSIS TEXT,TEST_TYPE TEXT,UPLOAD_DATE TEXT,READING_DATE_TIME TEXT,USER_NAME TEXT,NAME_FLAG TEXT,IS_DELETE TEXT,REPORT_STATUS TEXT)')
      .then(res => console.log('Executed SQL'))
      .catch(e => console.log(e));

    this.sqlite.create({
      name: 'ckdManagment.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      db.executeSql('CREATE TABLE AL_USER_REPORT_UPLOAD (USER_ID  TEXT,REPORT_ID TEXT,TEST_TYPE TEXT,UPLOAD_FLAG TEXT)')
        .then(res => console.log('Executed SQL'))
        .catch(e => console.log(e));

      this.sqlite.create({
        name: 'ckdManagment.db',
        location: 'default'
      }).then((db: SQLiteObject) => {
        db.executeSql('CREATE TABLE AL_REPORT_ANALYSIS_TYPES (TEST_PARAMETER TEXT,TEST_VALUE TEXT,TEST_UNIT TEXT,TEST_RANGE TEXT,GENDER TEXT,MIN_RANGE TEXT,MAX_RANGE TEXT)')
          .then(res => console.log('Executed SQL'))
          .catch(e => console.log(e));

        // Create DB & folder in android & IOS device

        if (this.platform.is('android')) {
          console.log('Platform is android ');
          this.file.checkDir(this.file.externalApplicationStorageDirectory, 'ckdManagment').then(response => {
            console.log('Directory exists' + response);
          }).catch(err => {
            console.log('Directory doesn\'t exist' + JSON.stringify(err));
            this.file.createDir(this.file.externalApplicationStorageDirectory, 'ckdManagment', false).then(response => {
              console.log('Directory create' + response);
              console.log("Path " + this.file.externalApplicationStorageDirectory + "/ckdManagment")
            }).catch(err => {
              console.log('Directory no create' + JSON.stringify(err));
            });
          });
        } else if (this.platform.is('ios')) {
          console.log('Platform is ios ');
          this.file.checkDir(this.file.documentsDirectory, 'ckdManagment').then(response => {
            console.log('Directory exists' + response);
          }).catch(err => {
            console.log('Directory doesn\'t exist' + JSON.stringify(err));
            this.file.createDir(this.file.documentsDirectory, 'ckdManagment', true).then(response => {
              console.log('Directory create' + response);
              console.log("Path " + this.file.documentsDirectory + "/ckdManagment")
            }).catch(err => {
              console.log('Directory no create' + JSON.stringify(err));
            });
          });
        }

      }).catch(e => console.log(e));

    }).catch(e => console.log(e));
  }).catch(e => console.log(e));

}).catch(e => console.log(e));

}

presentLoading() {
if (this.loading) {
this.loading.dismiss();
}
return new Promise((resolve)=>{
resolve(this.loadingController.create({
message: ‘Please wait…’
}));
})
}

async dismissLoading(): Promise {
if (this.loading) {
this.loading.dismiss();
}
}

async onSubmit()
{

// To check internate connection added by Shubham
  if (navigator.onLine) {
      console.log('Internet is connected');
  } else {
      this.showAlert("Please do online login.")
      console.log('No internet connection');
  }

if (this.platform.is('android') || this.platform.is('ios')) {
  this.checkVersionMissmatch();
  }
  else{
    this.doLogin()
  }


  // this.themesService.onNetworkChange().subscribe((status: ConnectionStatus) => {
  //   if (status == ConnectionStatus.Online) {
  //     console.log("online login")
    
  //   if (this.platform.is('android') || this.platform.is('ios')) {
  //     this.checkVersionMissmatch();
  //     }
  //     else{
  //       this.doLogin()
  //     }
  //   }
  //     else{
  //       alert("Please do online login")
  //       console.log("You are offline")
  //     }

  // });

}

async doLogin()
{

this.presentLoading().then((loadRes:any)=>{
this.loading = loadRes
this.loading.present()
let { formObj } = this;
this.userForm;

this.userForm.value["ID"] = this.userForm.value.username;

console.log("Login ID::" + this.userForm.value);


this.userForm.value['LOCK_STATUS'] = 'U';

let data = [];
let updateData = [];
console.log("user form data::::" + (this.userForm));
this.ID = this.userForm.value.username;


this.loginservice.userLogin(this.userForm.value).subscribe(async serverRes => {

  if (this.platform.is('desktop')) {
    
    localStorage.setItem('ID', this.ID);
    console.log("Sesion ID login set" + this.ID);
    // localStorage.setItem(key, JSON.stringify(myObj));

  }
  console.log('Server Response ' + JSON.stringify(serverRes["message"][0]));
  var serverResponse = serverRes["message"][0];
  console.log("serverResponse  ", serverRes["message"].length)
  if (serverRes["message"].length > 0) 
  {
    let selectData = [this.ID];

    data.push(serverResponse.ID, serverResponse.PASSWORD, serverResponse.FIRST_NAME, serverResponse.MIDDLE_NAME, serverResponse.LAST_NAME, serverResponse.EMAIL, serverResponse.MOBILE_NUMBER, serverResponse.GENDER, serverResponse.DOB, serverResponse.LINE1, serverResponse.LINE2, serverResponse.LINE3, serverResponse.CITY, serverResponse.PIN_CODE,serverResponse.COUNTRY_CODE);
    updateData.push(serverResponse.FIRST_NAME, serverResponse.MIDDLE_NAME, serverResponse.LAST_NAME, serverResponse.EMAIL, serverResponse.MOBILE_NUMBER, serverResponse.GENDER, serverResponse.DOB, serverResponse.LINE1, serverResponse.LINE2, serverResponse.LINE3, serverResponse.CITY, serverResponse.PIN_CODE, serverResponse.COUNTRY_CODE,serverResponse.ID);
    console.log("Data Array " + data);
   
    if (serverResponse.ID === this.userForm.value.username && serverResponse.PASSWORD === this.userForm.value.password){
    
      if (this.platform.is('android') || this.platform.is('ios')) {
      this.sqlite.create({
        name: 'ckdManagment.db',
        location: 'default'
      }).then(async (db: SQLiteObject) => {

      await db.executeSql('SELECT * FROM USERINFO where ID=? ', selectData)
        .then( async selRes => {

          console.log("Select Response ", JSON.stringify(selRes));
          console.log("Select Response length ", selRes.rows.length);
          if (selRes.rows.length == 0) {

            this.sqlite.create({
              name: 'ckdManagment.db',
              location: 'default'
            }).then(async (db: SQLiteObject) => {
             await db.executeSql('INSERT INTO USERINFO (ID ,PASSWORD,FIRST_NAME,MIDDLE_NAME  ,LAST_NAME ,EMAIL ,MOBILE_NUMBER,GENDER  ,DOB,LINE1 ,LINE2 ,LINE3 ,CITY  ,PIN_CODE,COUNTRY_CODE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)', data)
                //db.executeSql('INSERT INTO USERINFO (ID ,PASSWORD ) VALUES (?, ?)', data)
                .then(async insertRes => {
                  console.log("INSERT Response " + insertRes);
                await  this.insertUploadreportData();
                })
            }
              , err => {
                // this.loadingController.dismiss();
                this.dismissLoading();
                console.log('login insert error :: ' + JSON.stringify(err.status));
                if (err.status == 500) {
                  this.showerrorAlert();
                }
              }
            )
          }
          else {
            this.sqlite.create({
              name: 'ckdManagment.db',
              location: 'default'
            }).then(async (db: SQLiteObject) => {

              db.executeSql("UPDATE USERINFO SET FIRST_NAME= ? ,MIDDLE_NAME= ?  ,LAST_NAME= ? ,EMAIL = ? ,MOBILE_NUMBER= ? ,GENDER= ? ,DOB= ? ,LINE1= ? ,LINE2= ? ,LINE3= ? ,CITY= ? ,PIN_CODE= ?,COUNTRY_CODE= ? where ID = ?", updateData)
                .then(async res => {
                  console.log("UPDATE Response ", res);
                  await this.insertUploadreportData();
                })
            }
              , err => {
                //  this.loadingController.dismiss();
                this.dismissLoading();
                console.log('login update error ::' + JSON.stringify(err.status));
                if (err.status == 500) {
                  this.showerrorAlert();
                }

              }
            )
          }


        })
     }, err => {

      // this.loadingController.dismiss();
      this.dismissLoading();
      console.log('login select error ::' + JSON.stringify(err.status));
      if (err.status == 500) {
        this.showerrorAlert();
       }

      }
     )

    }

  
    else{
      // this.loadingController.dismiss();
      this.dismissLoading();
      this.login();  
    }

   }
   else{
    this.dismissLoading();
    this.showerrorAlert();
   }
  }
  else {
    // this.loadingController.dismiss();
    // this.showerrorFailedAlert();
    if (this.platform.is('android') || this.platform.is('ios'))
    {
       await this.insertUploadreportData();
    }
    else
    {
      this.dismissLoading();
      this.login();
    }
  }     
},
  err => {
    // this.loadingController.dismiss();
    this.dismissLoading();
    console.log('login err::' + JSON.stringify(err.status));
    if (err.status == 500) {
      this.showerrorAlert();
    }
    // else{
    //   this.showAlert();
    // }

  }
);

})
}

async insertreportTypeData() {
await this.loginservice.getReportTypes().subscribe(getResp => {

  var serverAnalysisResp = getResp["message"];
  console.log("getReportTypes Response " + JSON.stringify(serverAnalysisResp.length));

  console.log("getReportTypes Response " + JSON.stringify(serverAnalysisResp));
  if (serverAnalysisResp.length > 0) {

    this.sqlite.create({
      name: 'ckdManagment.db',
      location: 'default'
    }).then(async (db: SQLiteObject) => {

    await  db.executeSql("DELETE from AL_REPORT_ANALYSIS_TYPES ", [])
        .then(async deleteRes => {

          console.log("DELETE Response " + JSON.stringify(deleteRes));


          serverAnalysisResp.forEach(element => {
            var insertArr = [];
            insertArr.push(element.TEST_PARAMETER, element.TEST_VALUE, element.TEST_UNIT, element.TEST_RANGE, element.GENDER,element.MIN_RANGE,element.MAX_RANGE);
            console.log("insertArr Response " + JSON.stringify(insertArr));
            this.sqlite.create({
              name: 'ckdManagment.db',
              location: 'default'
            }).then(async (db: SQLiteObject) => {
             await db.executeSql('INSERT INTO AL_REPORT_ANALYSIS_TYPES (TEST_PARAMETER,TEST_VALUE,TEST_UNIT,TEST_RANGE,GENDER,MIN_RANGE,MAX_RANGE) VALUES (?, ?, ?, ?, ?,?,?)', insertArr)
                //db.executeSql('INSERT INTO USERINFO (ID ,PASSWORD ) VALUES (?, ?)', data)
                .then(async insertRes => {
                  console.log("INSERT AL_REPORT_ANALYSIS_TYPES Response " + JSON.stringify(insertRes));
                })
            }
              , err => {
                // this.loadingController.dismiss();
                this.dismissLoading();
                console.log('AL_REPORT_ANALYSIS_TYPES insert error :: ' + JSON.stringify(err.status));
                this.loadingController.dismiss();
                if (err.status == 500) {
                  this.showerrorAlert();
                }
              }
            )
          });

       //  await this.insertUploadreportData();
        // this.loadingController.dismiss();
        this.dismissLoading();
        this.login();  
          

        })
    })

  } else {
    // this.loadingController.dismiss();
    this.dismissLoading();
    this.login();
  }

})

}

async insertUploadreportData() {
var userID=[this.ID];

await this.loginservice.getUploadReportTypes(this.ID,“Login”).subscribe(getResp => {

  var serverAnalysisResp = getResp["message"];
  var response= getResp["message"];
   console.log("getReportUpload Response " + JSON.stringify(getResp["message"]));
   console.log("getReportUpload Response " + JSON.stringify(serverAnalysisResp.length));

  if (response != "No records found") {

    this.sqlite.create({
      name: 'ckdManagment.db',
      location: 'default'
    }).then(async( db: SQLiteObject) => {

     //await db.executeSql("DELETE from AL_USER_REPORT_DETAILS where report_entry_type='U' and USER_ID=?", userID)
     await db.executeSql("DELETE from AL_USER_REPORT_DETAILS where USER_ID=?", userID)   
     .then(async deleteRes => {

          console.log("DELETE Response " + JSON.stringify(deleteRes));


          serverAnalysisResp.forEach(element => {
            var insertArr = [];
            insertArr.push(element.USER_ID, element.REPORT_ID, element.REPORT_ENTRY_TYPE, element.REPORT_TEST_VALUES, element.DIAGNOSIS , element.TEST_TYPE, element.UPLOAD_DATE,element.READING_DATE_TIME,element.USER_NAME,element.NAME_FLAG,element.IS_DELETE,element.REPORT_STATUS);
            console.log("insertArr Response " + JSON.stringify(insertArr));
            this.sqlite.create({
              name: 'ckdManagment.db',
              location: 'default'
            }).then(async (db: SQLiteObject) => {
             await db.executeSql('INSERT INTO AL_USER_REPORT_DETAILS (USER_ID,REPORT_ID,REPORT_ENTRY_TYPE,REPORT_TEST_VALUES, DIAGNOSIS,TEST_TYPE,UPLOAD_DATE,READING_DATE_TIME,USER_NAME,NAME_FLAG,IS_DELETE,REPORT_STATUS) VALUES (?, ?, ?, ?, ?, ?, ?,?,?, ?,?,?)', insertArr)
                //db.executeSql('INSERT INTO USERINFO (ID ,PASSWORD ) VALUES (?, ?)', data)
                .then(insertRes => {

                 
                  console.log("INSERT AL_USER_REPORT_DETAILS Response " + JSON.stringify(insertRes));
                })
            }
              , err => {
                //  this.loadingController.dismiss();
                this.dismissLoading();
                console.log('AL_USER_REPORT_DETAILS insert error :: ' + JSON.stringify(err.status));
                if (err.status == 500) {
                  this.showerrorAlert();
                }
              }
            )
          });
        // await this.loadingController.dismiss();
          //this.login();
         await this.insertreportTypeData();
        })
    })
    

    

  } else {
    // this.loadingController.dismiss();
    // this.login();       
    this.insertreportTypeData();
    console.log("No data uploaded in AL_USER_REPORT_DETAILS");
  }

})

}

signup() {
this.router.navigateByUrl(‘/signup’);
// this.loginservice.simpleLoader();

}

login() {
//this.router.navigateByUrl(‘/dashboard’);
let navigationExtras: NavigationExtras = {
queryParams: {
‘ID’: this.ID,
‘DOB’: this.DOB
// ‘person_id’ : this.person_id

  }
};
this.router.navigate(['/dashboard'], navigationExtras);

}

forgotPasswordScreen() {
this.router.navigateByUrl(‘/forgot-password’);

}

resetPasswordScreen() {
this.router.navigateByUrl(‘/reset-password’);

}

// async showAlert() {
// const alert = await this.alertController.create({
// // header: ‘Alert’,
// cssClass: ‘my-custom-class’,
// subHeader: ‘Login sucessfully’,
// // message: ‘This is an alert message.’,
// buttons: [‘OK’]
// });

// await alert.present();
// }

async showAlert(message_alert) {
const alert = await this.alertController.create({
// header: ‘this.showAlert’,
cssClass: ‘my-custom-class’,
subHeader: message_alert,
buttons: [‘OK’]
});
await alert.present();
}

async showerrorAlert() {
const alert = await this.alertController.create({
// header: ‘Alert’,
cssClass: ‘my-custom-class’,
subHeader: ‘Login failed. Please check User ID or Password.’,
// message: ‘This is an alert message.’,
buttons: [‘OK’]
});

await alert.present();

}
async showerrorFailedAlert() {
const alert = await this.alertController.create({
// header: ‘Alert’,
cssClass: ‘my-custom-class’,
subHeader: ‘Data not found please signup again’,
// message: ‘This is an alert message.’,
buttons: [‘OK’]
});

await alert.present();

}

async showForgotAlert() {
const alert = await this.alertController.create({
// header: ‘Alert’,
cssClass: ‘my-custom-class’,
subHeader: ‘New password has been sent to your registered email ID’,
// message: ‘This is an alert message.’,
buttons: [‘OK’]
});

}

showLoader() {
this.loginservice.simpleLoader();
}

async initializeApp(){

  this.appVersion.getVersionNumber().then(
    (versionNumber) => {
      this.app_version = versionNumber;
      console.log("app_version is :::"+this.app_version)
    },
    (error) => {
      console.log(error);
    });

}

async checkVersionMissmatch(){
var deviceType=“”;

if (this.platform.is('android')) {
  deviceType="A";
}
else  if (this.platform.is('ios')){
  deviceType="I";
}
else{
    
}
this.loginservice.getAppVersionDetails(deviceType).subscribe(async getResp => {

  console.log(JSON.stringify(getResp));

  var serverAppVersionResp = getResp["message"][0];
  
   console.log("getReportUpload Response " + JSON.stringify(getResp["message"]));
   //console.log("getReportUpload Response " + JSON.stringify(serverAppVersionResp.length));
   var checkVersion =serverAppVersionResp.APP_VERSION;
   var appLink = serverAppVersionResp.APP_LINK;
  
  console.log("CKD version is:::"+checkVersion)
  console.log("CKD app link is:::"+appLink)

if ( checkVersion == this.app_version )
{
  console.log("Version is matched successfully ");
  this.doLogin();
}
else{
  console.log("Version is Missmatch ");
  console.log("Inside delete alert")
  let alert =  await this.alertController.create({
    subHeader: 'Confirm delete',

    message: 'Version Missmatch..! Do you want to download updated application?',
    buttons: [
      {
        text: 'No',
        cssClass: 'buttonCssNo',
        handler: () => {
          console.log('Cancel clicked No');
        }
      },
      {
        text: 'Yes',
        cssClass: 'buttonCssYes',
        handler: () => {
          console.log('Clicked Yes ');
          // this.presentLoading().then((loadRes: any) => {
          //   this.loading = loadRes;
          //   this.loading.present();
            
          // });

        //   const browser = this.iab.create(appLink,'_blank');

          
        //       browser.on('loadstop').subscribe(event => {
        //       console.log("load stop", event)
        //       browser.show();
          
        //       browser.executeScript({
        //         code: ` //alert will not work here 
        //               console.log("HELLO");
        //         `
        //       })
             

        //    // browser.close();
        // });
        window.open(appLink,'_system');
      }
      }
    ]
  })
 await alert.present();

}

});
}

enableDarkTheme()
{

this.themesService.themeFlag = true;
console.log("this.themesService.themeFlag Login ",this.themesService.themeFlag)
this.themesService.enableDark();

}

enableLightTheme()
{
this.themesService.themeFlag = false;
console.log("this.themesService.themeFlag Login ",this.themesService.themeFlag)
this.themesService.enableLight();
}

checkNetwork(){
this.themesService.onNetworkChange().subscribe((status: ConnectionStatus) => {
if (status == ConnectionStatus.Online) {
console.log(“connetion Status shubham”)
}
});
}

}