hello,
i follow this tuto https://youtu.be/CFoG0xkgVlE from Simon Grimm to check connectivity.
Two remarks :
-
displaying status network works fine only if i navigate and come back to the page.
-
toast message seems to works only with the last value
I really love to not have to navigate and come back to display the network status.
here is “my” code :
network service :
import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network/ngx';
import { BehaviorSubject, Observable,of} from 'rxjs';
import { ToastController, Platform } from '@ionic/angular';
export enum ConnectionStatus {
Online,
Offline
}
@Injectable({
providedIn: 'root'
})
export class Network2Service {
public status: BehaviorSubject<ConnectionStatus> = new BehaviorSubject(ConnectionStatus.Offline);
constructor( private toastController: ToastController, private plt: Platform) {
this.plt.ready().then( ()=>{
this.initializeNetworkEvents();
let status = this.network.type !== 'none' ? ConnectionStatus.Online : ConnectionStatus.Offline;
this.status.next(status);
});
}
public initializeNetworkEvents(){
console.log('initialize network events');
this.network.onDisconnect().subscribe( ()=>{
if(this.status.getValue() === ConnectionStatus.Offline){
console.log('We are Offline');
this.updateNetworkStatus(ConnectionStatus.Offline);
}
});
this.network.onConnect().subscribe( ()=>{
if(this.status.getValue() === ConnectionStatus.Online){
console.log('We are Online');
this.updateNetworkStatus(ConnectionStatus.Online);
}
});
}
private async updateNetworkStatus(status: ConnectionStatus) {
this.status.next(status);
let connection = status == ConnectionStatus.Offline ? 'Offline' : 'Online';
let toast = this.toastController.create({
message: `You are now ${connection}`,
duration: 3000,
position: 'middle'
});
toast.then(toast => toast.present());
}
public onNetworkChange(): Observable<ConnectionStatus> {
return this.status.asObservable();
}
public getCurrentNetworkStatus(): ConnectionStatus {
return this.status.getValue();
}
}
component :
...
public status:Observable<ConnectionStatus>;
....
ngOnInit() {
this.network2Service.onNetworkChange().subscribe( status=>this.status=of(status) );
}
view
...
<ion-grid>
<ion-row><ion-col>Status</ion-col></ion-row>
<ion-row><ion-col>{{ status | async }}</ion-col></ion-row>
</ion-grid>
...
i’ll try w/out async too: {{status}} , same result.
So how can i display " status" network in live (without navigate and come back) ?
Thank you for help
n