The Network plugin is having issues with the PWA application in Ionic 4

I've been utilizing the network plugin successfully on native/Cordova devices. However, I have encountered an issue when trying to use it on a PWA app (specifically when there is no wifi connection). Can anyone shed light on why this might be happening? As per the documentation provided, it should work on the browser as well.

Note: I followed the instructions in this document to create the PWA application.

network-state.ts

import { Injectable } from '@angular/core';
import { Subscription } from 'rxjs';
import { Network } from '@ionic-native/network/ngx';
import { ShowToastService } from './show-toast.service';

@Injectable({
  providedIn: 'root'
})
export class NetworkStateService {

  private connectSubscription$: Subscription = null;

  constructor(private network: Network,
    private showToastService: ShowToastService) { }

  WatchConnection() {
    if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
    this.connectSubscription$ = this.network.onDisconnect().subscribe(() => {
      this.showToastService.showNetworkStateErrorToast('Your internet seems to be down! Please check your network settings!');
      if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
      this.connectSubscription$ = this.network.onConnect().subscribe(() => {
        setTimeout(() => {
          this.showToastService.toast.dismiss();
          if (this.network.type === 'wifi' || this.network.type === '4g' || this.network.type === '3g' || this.network.type === '2g' || this.network.type === 'cellular' || this.network.type === 'none') {
            this.showToastService.showNetworkStateSuccessToast('Internet connection available!');
            this.WatchConnection();
          }
        }, 3000);
      });
    });
  }

}

app.component.ts

 async initializeApp() {
    await this.platform.ready();
    this.statusBar.styleDefault();
    this.splashScreen.hide();

    this.networkStateService.WatchConnection();// here

  }

Answer №1

When working with Ionic Native, plugins are only called when cordova is available. In the code snippet here, a check is made to verify the presence of cordova in the window object, and if it's not found, a warning is logged.

If you're following a guide that instructs you to publish as a PWA using the standard Angular browser build, cordova will not be included - which is correct. As a result, Ionic Native behaves as expected due to the absence of cordova in the build.

An alternative solution could be to leverage Capacitor, which offers a network plugin and integrates well with existing deployment tools like Angular and PWAs.

For more information, check out this getting started guide and this helpful reference guide

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

Angular: Using Observable.timer() and switchMap to delay function execution

This is how I approach the situation: filter(value) { this.backendCall(value) } To prevent my method from being called repeatedly for every keystroke, I aim to introduce a pause between backend requests using Observable.timer() and switch ...

Exploring the capabilities of Angular2 and Jasmine through testing

I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...

Trouble with loading images on Angular Application

After successfully building and deploying my Angular App using the build command on the cli with the deploy-url option as shown below: ng b -deploy-url /portal/ I encountered an issue where everything in the assets folder was showing up as 404 not found ...

Exploring the possibilities of customizing themes in Angular Material with Stylus for Angular 5

My project is currently utilizing the "stylus" CSS pre-processor instead of SCSS. I am interested in incorporating Angular Material themes and switching between them. While I can find documentation for SCSS, I am struggling to find resources for stylus. ...

The NgRx Effect causing an endless cycle of HTTP requests

I am currently experiencing the following effect: initCompaniesAndSetCompanyEffect$: Observable<Action> = createEffect( (): Observable<Action> => this.actions$.pipe( ofType<changeCompanyActions.InitCompaniesAction>( ...

Could you provide an explanation of the styled() function in TypeScript?

const Flex = styled(Stack, { shouldForwardProp: (prop) => calcShouldForwardProp(prop), })<LayoutProps>(({ center, autoWidth, autoFlex, theme }) => ({ })); This syntax is a bit confusing to me. I understand the functionality of the code, b ...

What is the rationale behind Angular's decision to use cdr.markForCheck() instead of cdr.detectChanges() in the async

Regarding Angular, I have a question: Why does the Angular async pipe use cdr.markForCheck() instead of cdr.detectChanges()? I have noticed two main differences between these two approaches: markForCheck() marks the path all the way up to the root compo ...

Error: The function was expecting a mapDiv with the type of Element, but instead undefined was passed - google

I have a map within a div tagged with #mapa. Whenever I try to plot a route on the map, it refreshes. I don't want the map to refresh, and here is the code I currently have: <div style="height: 500px; width: auto;" #mapa> <google-map heigh ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

Sharing API Results with All Components in Angular 7 using BehaviorSubject

My goal is to optimize an API call that fetches data about the current user (such as their username, full name, group memberships, email address, and more) by ensuring it's only made once per user session and that the data is shared across all compone ...

Angular 2, React, or any other modern framework.getList()?.map

I have experience working on multiple angular 1 projects and I absolutely enjoyed it. We have several upcoming projects where I need to recommend JavaScript frontend libraries/frameworks. With the decline of angular 1 and mixed reviews about angular 2&apos ...

"Encountering Devextreme Reactive Errors while navigating on the main client

Attempting to integrate Devextreme with Material Ui in my Typescript React app has been a challenge. Despite following the steps outlined in this documentation and installing all necessary packages, I am encountering issues. I have also installed Material ...

The selected value of the PrimeNG p-checkbox cannot be determined using a function when binding to [ngModel]

These are the rows of my custom p-table <tr> <td>{{user.userName}}</td> <td>{{use.userSurname}}</td> <td *ngFor="let group of groups"><p-checkbox [(ngModel)]="showVal ...

Navigating route parameters in Angular Universal with Java

I am currently developing a web application using Angular 5 with Server Side Rendering utilizing Angular Universal for Java. The project repository can be found here. One of the challenges I am facing is with a parameterized route defined in Angular as /pe ...

Troubleshooting problem in Grunt-TS, Grunt, watch/compile, and Dropbox integration

UPDATE: Recently, I've been experiencing some issues with another computer when it comes to watching and compiling. It seems like the tscommandxxxxxx.tmp.txt files that are generated during compilation might be causing the trouble... sometimes they ar ...

List out the decorators

One query is bothering me - I am attempting to create my own version of Injectable and I need to determine if a specific decorator exists in my Class. Is there a way to list all decorators of a class? Let's take the example below. All I want to know i ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

Angular 2 Return {responseBody: "assigned variable with [object Object]"}

In my Angular 2 application, I am encountering an issue where I am sending a variable from a service to a component. In the template, the variable appears as expected, however, when attempting to send this variable to a PHP script using POST, I receive [ ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

Enhancing Ionic's functionality by including extra access control to permit origin in response headers

Dealing with the issue of Ionic/Angular adding extra access control allow origin to response headers. How can this be prevented? My Nginx server currently has CORS enabled add_header 'Access-Control-Allow-Origin' '*' always; add_header ...