Observing network events with Ionic 2, RxJS5, and the Cordova network plugin

Is it possible to create an RxJS observable using the fromEvent method based on the Cordova network connection plugin?

I am attempting this with Ionic 2.

I have noticed that the Cordova network connection plugin offers two events (online/offline). How can I subscribe to these events using RxJS?

Here is an example of what I am trying to achieve:

const offline$ = Observable.fromEvent(CORDOVA_OFFLINE_EVENT);
offline$.subscribe(
    function (connectionType) {
        console.log("connectionType", JSON.stringify(connectionType));
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    }
);

Answer №1

To achieve this, simply follow the instructions provided in the documentation (

document.addEventListener("offline", onOffline, false);
). In the event handler, you have the option to emit with an EventEmitter or, if preferable, use observables by dispatching a custom event to the document and creating
Observable.fromEvent(document, 'nameofevent')
.

For instance:

window.addEventListener('offline', this.onOffline);
onOffline(e) {
        var event = new CustomEvent('onoffline');
        event['offlineTimestamp'] = new Date()
        document.dispatchEvent(event);
    }

Then, simply do

this.networkObservable = Observable.fromEvent(document, 'onoffline');

Alternatively, instead of using CustomEvent, you can utilize an EventEmitter that emits within the handlers:

networkEmitter = new EventEmitter();
window.addEventListener('offline', onOffline);
    onOffline(e) {
            this.networkEmitter.emit('wentOffline');
        }

You can then subscribe to the EventEmitter or Observable for further functionality :)

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

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

Issue with Dialogue in React Native - The property 'children' is not found in the types 'intrinsicAttributes' and '

I attempted to utilize this sample code to create an alert dialog in my react native app, but I encountered an error on Dialog (marked with ***) stating TS2322: Type '{ children: Element[]; visible: boolean; onDismiss: () => void; }' is not ...

Tips for identifying and handling errors in Playwright

I'm going crazy trying to handle a TimeoutError that I know is coming. Currently, I'm testing the Hidden Layers scenario from UI Testing Playground in Playwright Node.js and I want to see if there's a way to prevent the TimeoutError from cau ...

When using react-hook-form within a .map() function, it encounters an issue causing it to fail - specifically, a TypeError message stating "Cannot read properties of undefined (reading '

Confused and frustrated here, I can't seem to get this form working properly. I have a Checkbox component that works fine when not in a loop, but as soon as I try to integrate it into a loop, everything breaks. Checkbox.tsx const Checkbox = React.for ...

Checking for duplicate entries in an array created with the Angular form builder

I am currently utilizing angular6 reactive form with form builder and form array. The issue I am encountering is duplicate subject entries from the drop down in the form array. How can I implement validation to prevent duplicate entries in the form array? ...

The type 'Node' does not have the required attributes

Could anyone shed some light on what might be causing the issue described below? Your insights are greatly appreciated. The problem lies within the line of code: clone = thead.cloneNode(true); The error message reads: 'Type 'Node' is missin ...

Angular Ant Design Pagination

Currently, I am working on implementing cards and pagination in Angular version 7 using Ant Design. While following the guidelines on the Ant Design website () for cards, I noticed that it does not provide instructions on how to combine cards with pagina ...

Tips for creating a custom observable that reacts to multiple data subscriptions

After spending countless hours struggling, I found a way to create a custom observable that relies on multiple nested subscriptions to other observables. It involves calling a function, subscribing to check the value of the observable, determining which ...

Step-by-step guide on converting a file upload to a JavaScript object in Angular 11

I need to parse a JSON file into an object before sending it for validation in an API call. The current code is not working and the API requires an object. <label class="form-label required" for="file">File</label> <label ...

TypeScript: Unforeseen reserved term

In my WebStorm IDE & Node.js project, I successfully utilized a file called "mongo-manager.ts" in the routes\index.js file without any issues. However, I made two changes: Instead of ignoring WebStorm's prompt to compile TypeScript to JavaScrip ...

Having trouble with the Typescript validator in my Angular IDE Eclipse Plugin - it doesn't seem

If i enter wrong code in typescript editor it doesn't show me any compile time error. I don't know why typescript validator doesn't work. I am using eclipse Neon.3 Release (4.6.3) with angular IDE plugin. Do i have to add anything further to ...

Can someone please provide guidance on how I can access the current view of a Kendo Scheduler when switching between views, such as day view or week

<kendo-scheduler [kendoSchedulerBinding]="events" [selectedDate]="selectedDate" [group]="group" [resources]="resources" style="height: 600px;" [workDayStart]="workDayStart" [workDayEnd] ...

Prevent Angular Router from Initiating NavigationStart

Can the NavigationStart event be prevented in Angular? I am attempting to display a customized confirmation modal when the user attempts to switch routes. constructor(private router: Router) { if(val instanceof NavigationStart){ //Display th ...

"Enhance your user experience with dual notifications using the Angular2-to

Whenever I utilize the angular2-toaster packages, I find myself receiving duplicate notifications. Below is an example showcasing the usage of this package. I am unsure why this issue occurs, but I have noticed that simply reloading my angular2 applicatio ...

Typescript: Subscribed information mysteriously disappeared

[ Voting to avoid putting everything inside ngOnit because I need to reuse the API response and model array in multiple functions. Need a way to reuse without cluttering up ngOnInit. I could simply call subscribe repeatedly in each function to solve the p ...

I am unable to npm install on a cloned ngx-datatable repository

Hello everyone! After observing for quite some time, I have finally decided to ask a question and share it with the community for the benefit of others. When I clone certain projects and run npm install (even from my work's gitlab), everything works ...

MaterialUI Divider is designed to dynamically adjust based on the screen size. It appears horizontally on small screens and vertically on

I am currently using a MaterialUI divider that is set to be vertical on md and large screens. However, I want it to switch to being horizontal on xs and sm screens: <Divider orientation="vertical" variant="middle" flexItem /> I h ...

What is the best way to change the number 123456789 to look like 123***789 using either typescript or

Is there a way to convert this scenario? I am working on a project where the userID needs to be displayed in a specific format. The first 3 characters/numbers and last 3 characters/numbers should be visible, while the middle part should be replaced with ...

Retrieve ag grid from TypeScript file

I am currently utilizing ag-grid-angular in my Angular application to showcase data. I have a button that is located outside the ag grid, and when it is clicked, I need to retrieve all row data from the grid. I am aware that there is an API available for a ...

Leveraging a returned value from a function in Typescript within a React component

I am currently facing a challenge where I need to extract values from a Typescript function and use them to dynamically render a React page. Specifically, the two values I am working with are the outputs of getIcon() and getSpaces(). This is how I attempt ...