Absence of a connectivity pop-up within Ionic 2

Whenever the app loads, my "network check" should run automatically instead of waiting for the user to click on the Check Connection button. I tried putting it in a function but couldn't get it to work. Can anyone help me identify the syntax error in my if states == ... statement?

Click to Check Connection Check Connection

    import {Component} from '@angular/core';
    import {NavController, Platform, AlertController} from 'ionic-angular';

    declare var navigator: any;
    declare var Connection: any;

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {

        constructor(public navCtrl: NavController, public platform: Platform, public alertCtrl: AlertController) { }

        checkNetwork() {
            this.platform.ready().then(() => {
                var networkState = navigator.connection.type;
                var states = {};
                states[Connection.UNKNOWN]  = 'Unknown connection';
                states[Connection.ETHERNET] = 'Ethernet connection';
                states[Connection.WIFI]     = 'WiFi connection';
                states[Connection.CELL_2G]  = 'Cell 2G connection';
                states[Connection.CELL_3G]  = 'Cell 3G connection';
                states[Connection.CELL_4G]  = 'Cell 4G connection';
                states[Connection.CELL]     = 'Cell generic connection';
                states[Connection.NONE]     = 'No network connection';

                // this. was missing
                let alert = this.alertCtrl.create({
                    title: "Connection Status",
                    subTitle: states[networkState],
                    buttons: ["OK"]
                });

                // This is the proper way to present the alert
                alert.present();
            });
        }

    }

Prompt Displayed If No Connection

    import {Component} from '@angular/core';
    import {NavController, Platform, AlertController} from 'ionic-angular';

    declare var navigator: any;
    declare var Connection: any;

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {

        constructor(public navCtrl: NavController, public platform: Platform, public alertCtrl: AlertController) { }

       ionViewDidLoad() {
            this.platform.ready().then(() => {
                var networkState = navigator.connection.type;
                var states = {};
                states[Connection.NONE]     = 'No network connection';

                if (states == states[Connection.NONE]) {

                let alert = this.alertCtrl.create({
                    title: "Connection Status",
                    subTitle: states[networkState],
                    buttons: ["OK"]
                });

                alert.present();

                }

            });
        }

    }

Answer №1

The Navigator.connection feature is currently in an experimental phase and not supported on desktop browsers, so testing it may not yield useful results. It's important to keep in mind whether you are testing on a browser or a device. Your code could still be fine.</p>

<p>More information can be found here: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection</a></p>

<p><code>The navigator.connection.type property will return one of the following values:</p>

<pre><code>bluetooth
cellular
ethernet
none
wifi
wimax
other
mixed

If you set your condition to check for none, there shouldn't be any reason why it wouldn't work.

...
   navigator.connection.type === 'none' ? this.isOffline() : console.log('online');
}

isOffline(){
   return this.alertCtrl.create({
              title: 'Connection Status',
              subTitle: 'No network connection',
              buttons: ["OK"]
           }).present();
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to save data retrieved using jQuery JSONP

My current project involves fetching photo data from Flickr using a jQuery AJAX call with JSONP. However, instead of immediately using the data, I want to store it for future use. In some cases, users will be able to perform different queries on the pre-fe ...

Defining Higher Order Components in ReactJS: A comprehensive guide

Trying to wrap my head around Higher Order Components (HOC) in ReactJS with this simple example... I've got three files - First.js, Second.js, and App.js. How should I structure these files so that the computations done in the first file can be acces ...

Showing a collection of cards within a dynamic container set up in a 3x3 grid layout to start

In an attempt to showcase cards within a responsive container utilizing bootstrap and django, my goal is to create a 3x3 grid layout on extra-large screens with scrollable overflow that adjusts based on device width. Initially, I experimented with wrapping ...

Is Window.navigator malfunctioning on different browsers in Mac OS?

I'm attempting to access the navigator function in my project to share a specific URL, but I'm facing difficulties accessing it on Mac OS when using browsers other than Safari. Is there a solution to this issue? Below is the function I created f ...

Having difficulty making Skrollr compatible with BootStrap 3 single page wonder

I am completely new to JavaScript, which is why I decided to use Skrollr. However, I have been facing some challenges in getting Skrollr to work properly on my webpage. I added the following code at the end of my page: <script type="text/javascript" sr ...

Angular Datatables unable to locate DataTables with Webpack Encore configuration

As I've been updating a Symfony application from version 3.4 to 4.2.2, everything has been going smoothly until I encountered an issue with getting DataTables to work through yarn installation and webpack encore using angular-datatables. The Setup Pr ...

What are the possible reasons for a checkbox not being checked in React JS?

I've been working with react final form and I'm encountering an issue where I can't seem to get the checkbox to be properly checked. I'm not sure what mistake I might be making. Take a look at my code on CodeSandbox const AppWithIconTo ...

Error encountered when trying to load Ajax script

As a beginner in the learning process, my code may appear messy. I am currently wrapping up my second project, which is a photo viewer. On the main page, there is a navigation system that loads different sections of the website using ajax. Since this proje ...

Determine the hue of a specific location on a geometric surface

I'm currently working with THREE.js for my scene rendering and I have a complex question - how can I retrieve the color of a specific point on a geometry face? When I mention color, it's not just the face or material color that I'm interest ...

Execute the controller function once all asynchronous calls to the Angular service have finished

I have integrated the Angular Bootstrap Calendar using a custom cell template and cell modifier. Within my controller, I need to retrieve configuration data from a service that is required by the cellModifier function before it is executed. (function() { ...

What is the best way to alter the header in Django when a user is authenticated?

In my project, I have two headers: header.html and headersuccess.html. When a user is logged in, I need to change the header from header.html to headersuccess.html. How can I implement that? Here is an excerpt from my views.py file where I render loginsuc ...

Customize Material-UI FAB Hover Color

While working on my project, I encountered an issue with a floating action button that contains an SVG icon nested underneath it. Even though the SVG icon is not in the children prop of the FAB, hovering over the FAB or the SVG icon causes the FAB to chang ...

Can you suggest a simple method for implementing the "componentDidUpdate()" lifecycle method using just JavaScript?

I've been curious about replicating the componentDidUpdate() lifecycle method in JavaScript on my own. It got me thinking, how did React and Vue.JS create their own lifecycle methods? I attempted to study the minified version of Vue.JS but found it qu ...

Astro3.0 unable to locate images

I'm working on a simple astro project that is structured like this: └── src    ├── assets    │   └── images    │      └── blend.webp    ├── components    │   └── CoffeeCard.astro    ...

Angular throwing an error message: "ChildrenOutletContexts provider not found!"

I developed a basic testing application and encountered the error message - "No provider for ChildrenOutletContexts!" I have searched through various related posts but to no avail. Here is my project structure: The App Module contains the App Routing Modu ...

How come the Array object transforms into an empty state when an input file is passed as an array element in an ajax request without

When attempting to upload a file without assigning it to an array, the process works fine. However, when trying to assign the file object as an element of an array, $_FILES becomes empty. HTML <input type='file' name='image' class= ...

Issue with Gijgo grid not updating properly during change event

I'm currently working on an MVC 5 application and I've hit a roadblock with a particular view. This view contains a dropdown menu and a grid (Gijgo-grid). The grid's content is supposed to change based on the selected value from the dropdown ...

Regain Identification or Data using PHP, JavaScript, and MySQL

I'm currently working on a project and I'm facing a challenge in retrieving Id either in php or js. I have 2 rows in the same table in mySql: row 1 = id_answer and row 2 = text. I am using a foreach loop in my code to extract the text from the ...

Can you use `keyof` to create a template literal type?

Defined a form schema type example: type FormSchema = { username: string; settings: { theme: string; language: string } } Now, trying to define the Form Input type like this: type FormInput = { id: keyof FormSchema | `${keyof FormSchema}.${string}` } Enc ...

Creating an Interactive and Engaging 3D Experience on Facebook with the Power of Javascript API

Looking for suggestions on a 3D API in JavaScript that can be used to create immersive applications on Facebook. Is there something similar to this one: ? Appreciate any insights. ...