Sharing information between a cordova plugin and an Angular application

I have been working on an Angular/Cordova app and I am trying to pass the online/offline status to Angular:

export class AppComponent implements OnInit {
  isOff = false;
  constructor() {
    document.addEventListener('deviceready', onDeviceReady, false);
    function onDeviceReady() {
      document.addEventListener('offline', onOffline, false);
      document.addEventListener('online', onOnline, false);
      function onOffline() {
        alert('You are offline.');//It's working
        this.isOff = true;//Not functioning
      }
      function onOnline() {
        alert('You are Online.'); //It's working
        this.isOff = false; //Not functioning
      }
    }
  }
}

Answer №1

Implement arrow functions within constructor:

    document.addEventListener('deviceready', () => this.onDeviceReady(), false);
    document.addEventListener('pause', () => this.onPause(), false);
    document.addEventListener('resume', () => this.onResume(), false);
    document.addEventListener('offline', () => this.onOffline(), false);
    document.addEventListener('online', () => this.onOnline(), false);

Your Angular variable is now accessible.

onDeviceReady() {
    console.log('---onDeviceReady--->');
}

onPause() {
    console.log('---onPause--->');
}

onResume() {
    console.log('---onResume--->');
}

onOffline() {
    console.log('---onOffline--->');
    this.isOff = true;
}

onOnline() {
    console.log('---onOnline--->');
    this.isOff = false;
}

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

How to extract multiple literals from a string using Typescript

type Extracted<T> = T extends `${string}${'*('}${infer A}${')+'}${string}${'*('}${infer A}${')+'}${string}` ? A : never type Result1 = Extracted<'g*(a12)+gggggg*(h23)+'> // 'a12' | &a ...

Mastering the art of utilizing generic types efficiently within Higher Order Component structures

My parent component (Grid) passes props to a higher-order component (hoc), let me show you: <QuickBooksTable itemList={quickBooksList} /> Here is the QuickBooksTable component: export const QuickBooksTable = withIntegrationTable(props: : WithIntegra ...

"Within Angular 2+, the attribute referenced is not recognized as a valid property, even though it is explicitly defined within the @Input

The main goal here is to increase the vertical pixel count. <spacer [height]="200"></spacer> Initially facing an issue where an error message states that height is not a recognized attribute of spacer. To address this problem, I set up the fo ...

How to link data from a service to an Angular component in a way that ensures the component gets updated whenever there is new data in the service

When data is updated in a service, how can I ensure that the changes are reflected in a component? In my application's header, there is a button that allows users to switch between English and Spanish. However, while the text in the header (a compone ...

Guide on building an npm package that seamlessly allows for installation both locally and globally (-g) using webpack and typescript

As I work on developing an npm package with options for both local and global (-g) installations, I find myself puzzled by the distinctions between the src and lib directories and the purpose of the bin directory. In my previous projects, I typically util ...

What is the syntax for declaring a state variable as a Set data type in programming?

Struggling to establish a state variable in React using Typescript. Encountering an error when attempting to specify its type as Set. The purpose of this variable is to contain an array of objects. const [blocksList, setBlocksList] = useState<Set>([ ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

Tips for writing unit tests for clipboard copy functionality in an Angular application

How can we monitor the behavior of the clipboard.copy method? For const clipboard = TestBed.inject(Clipboard); spyOn(clipboard, 'copy').and.returnValue(true); An error warning pops up indicating that Argument of type '"copy"' ...

Approach to activate Required Field Validation while navigating through DatePicker form control

Within my Angular application, I have implemented Required Field Validation for a DatePicker component: <div class="form-group" [ngClass]="{ 'has-required':['injuryDate'].untouched && ['injuryDate'].invalid, ...

Problem with sequential promises

import { Observable } from 'rxjs/internal/Observable'; export function createHttpObservable(url: string) { console.log('Url is', url); return Observable.create(observer => { fetch(url) .then(response => { ...

Next.js displays an error when attempting to update the `AuthContextProvider` component while rendering the `Login` component

I have developed a basic next.js application that involves user login functionality through a graphql-api. The login process utilizes the react context-API to update the context once the user successfully logs in. Upon successful login, the intention is to ...

Is there a way to stop a for loop when the mouse hovers over a Google Map?

When hovering over markers on Google Maps, I am looping the data to display in an info window. Initially, the data is coming as expected, but when hovering over the same marker again, the data is adding to the existing data. Here is the StackBlitz URL fo ...

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

The template literal expression is invalid due to the "string | null" type when sending authorization

While working on implementing authorization, I encountered an error from Ts-eslint stating that there was an "Invalid type 'string | null' of template literal expression" when trying to execute the functionality. The data being retrieved from lo ...

Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface. The API is returning a list of objects with various properties, but I only require a few specific properties from the response object. Example of API Response: ...

Tips for utilizing a dropdown menu in Angular

<div> <label> Categories </label> <select> <option *ngFor = "let category of categories" [value] = "category" (click) = "onCategorySelected( category.name )"> ...

Is it possible to execute a node.js file using an AJAX request within a PhoneGap application

I am trying to make an ajax call to access a node.js file, but I am struggling to get it to work. Can someone please guide me on the correct URL format to use in the ajax call to access the node.js file? ...

Discover the return types in Typescript by inferring from a collection of functions within an

Imagine you have an object { num1: 1, num2: 2, str: "abc" } Your goal is to develop a function that accepts any similar object as the first parameter, and a custom selectors object as the second parameter. function fn<O extends object, ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...