Issue
I am working on an android app and I want to detect when my internet connection is available and not with this ionic plugin, cordova-plugin-network-information
but when i ran this command ionic cordova plugin add cordova-plugin-network-information
in my command prompt i got this error
Unexpected token in JSON at position 0
[ERROR] An error occurred while running subprocess cordova.
cordova.cmd plugin add cordova-plugin-network-information exited with exit code 1.
Re-running this command with the --verbose flag may provide more information.
even when i added the --verbose
to it, i still got the same error i am using windows 10, please how can i resolve this
Solution
The plugin gives you a lot of additional information about the nature of the connection, the strength of the signal, etc. But depending on your use case you may just try adding simple online/offline detection functionality using Web APIs:
connectivity.provider.ts:
import { Injectable } from '@angular/core';
import { Observable, fromEvent, merge, of} from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class ConnectivityProvider {
public appIsOnline$: Observable<boolean>;
constructor() {
this.initConnectivityMonitoring();
}
private initConnectivityMonitoring() {
if (!window || !navigator || !('onLine' in navigator)) return;
this.appIsOnline$ = merge(
of(null),
fromEvent(window, 'online'),
fromEvent(window, 'offline')
).pipe(map(() => navigator.onLine))
}
}
This way you have this code working across both hybrid builds and PWA and also avoid additional binary functionality concerns.
This provider can be imported in a component, injected via the constructor and then subscribed to the stream of boolean events:
this.connectivityProvider.appIsOnline$.subscribe(online => {
console.log(online)
if (online) {
// call functions or methods that need to execute when app goes online (such as sync() etc)
} else {
// call functions on network offline, such as firebase.goOffline()
}
})
Here is stackblitz: https://stackblitz.com/edit/ionic-angular-v5-z34sqf
So if you use Chrome's dev tools performance tab and simulate online/offline it works pretty reliably:
Answered By - Sergey Rudenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.