0

My main goal here is to detect if the internet connection is active or not in my website.

The following line of codes is functional in my http://localhost:8100/ but unfortunately when I deployed my website in Heroku, all of this functions in detecting the internet connection failed.

This Ion Alert Controller detects if network connection is active or not. but unfortunately this alert doesn't respond in my system after the deployment. Alert Controller must be called if no connection was detected.

If user press the RELOAD, the whole page will reload again to check if connectivity exist: enter image description here

This is the code for detecting network connectivity. I used this example: https://stackoverflow.com/a/57069101/13848366

app.component.ts

Note: I make createOnline$ Observable to detect automatically if the connection is change.

  connectionMsg: boolean;

  constructor(private alertController: AlertController) {

    this.createOnline$().subscribe(isOnline => {
      console.log(isOnline);
      if (isOnline == true) {
        this.connectionMsg = true;
      } else {
        this.connectionMsg = false;
        this.reloadPage();
      }
      console.log("Msg: " + this.connectionMsg);
    })

  }

  createOnline$() {
    return merge<boolean>(
      fromEvent(window, 'offline').pipe(map(() => false)),
      fromEvent(window, 'online').pipe(map(() => true)),
      new Observable((sub: Observer<boolean>) => {
        sub.next(navigator.onLine);
        sub.complete();
      })
    );
  }

  //THIS IS THE ION ALERT CONTROLLER WITH window.location.reload() to reload the whole page.
  async reloadPage() {
    const alert = await this.alertController.create({
      header: 'Connection Lost',
      message: 'Try to <strong>reload</strong> the page.',
      backdropDismiss: false,
      buttons: [
        {
          text: 'Reload',
          handler: () => {
            window.location.reload();
          }
        }
      ]
    });

    await alert.present();
  }
  • 1
    When you say that "all of your functions fail", what _exactly_ does that mean? What do you expect to see, what happens instead? – Ingo Bürk Nov 27 '21 at 21:32
  • @Ingo I mean my function in detecting no internet connection just failed. Ion alert controller doesn't respond in my system after the deployment. Sorry for the lack of info in that part, I will edit it again. – John Paulo A. Geronimo Nov 28 '21 at 00:20
  • So are you saying that `createOnline$` always emits `true`? I wonder if it is emitting more that one time. Do you notice multiple log messages? – BizzyBob Nov 29 '21 at 03:59
  • @IngoBürk It normally runs in my console.log but my Ion Alert Controller doesnt respond even the createOnline is false. – John Paulo A. Geronimo Nov 29 '21 at 11:56
  • Do you try a production build locally? I would presume it would fail then too, maybe something is getting accidently tree-shaken? – Daniel Gimenez Nov 29 '21 at 13:56

2 Answers2

1

May be this could help:

import {HostListener} from '@angular/core';
@HostListener('window:online', ['$event'])
onLine(e:any){
 // do something
}
A. Sinha
  • 2,666
  • 3
  • 26
  • 45
0

u can try use the offical plugin for ionic eg:

NO INTERNET COMPONENT.TS
    import { Network } from '@ionic-native/network/ngx';

    constructor(
        private router: Router,
        private network: Network, 
        private dialog: DialogService,
        public translate: TranslateService) { }
    
      tryAgain() {
        const networkState = this.network.type;
    
        if (networkState !== this.network.Connection.NONE) {
          this.router.navigate(["/tabs/marketplace/"], { replaceUrl: true });
        }
        else {
          this.dialog.showAlert(HeaderTypes.NOTIFICATION, this.translate.instant("ERRORS.STILL_NO_CONNECTION"), ['ok']);
        }
    
      }

APP INTERCEPTOR.TS

export class Http_Interceptor implements HttpInterceptor{
   ...

  intercept(req: HttpRequest<any>, next: HttpHandler) {

        this.disconnectSubscription = 
         this.network.onDisconnect().subscribe((res) => {
            //this.router.navigate(['no-internet']);
            return res.returnValue;
        });

        if (this.disconnectSubscription !== true) {
            ...

            if (token != null) {
               ...
                })
            }
            return next.handle(authReq).pipe(
                map((event: HttpEvent<any>) => {
                    if (event instanceof HttpResponse) {
                        //silence its golden
                    }
                    return event;
                }),
                catchError((error: HttpErrorResponse) => {
                    switch (error.status) {

                        case 0:
                            this.router.navigate(['no-internet']);
                            break;
                       ... ect
                    }

                    return throwError(error);
                }), share());
        }

        else {
            this.router.navigate(['no-internet']);
        }


    }
}
Kevin Dias
  • 1,043
  • 10
  • 28