app.module.ts
add the service in your providers
@NgModule({
...
providers: [NetworkService],
...
})
app.component.ts
infoConnection$ = this.networkService.infoConnection$;
constructor(private networkService: NetworkService) {
this.networkService.infoConnection$.subscribe(infoConnection => {
console.log(infoConnection)
})
}
network.service.ts
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Network } from '@ionic-native/network';
import { Subject } from 'rxjs/Subject';
import { NotificationService } from './notification-service';
@Injectable()
export class NetworkService {
info: any = {
connected: true,
type: "none"
};
disconnectSubscription: any;
connectSubscription: any;
private infoConnection = new Subject<any>();
infoConnection$ = this.infoConnection.asObservable();
constructor(
private network: Network,
private platform: Platform,
private notificationService: NotificationService,
) {
this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {
this.sendStatus();
});
this.connectSubscription = this.network.onConnect().subscribe(() => {
this.sendStatus();
});
}
sendStatus() {
if (this.platform.is("cordova")) {
setTimeout(() => {
this.info = {
connected : this.isConnected(),
type: this.getConnectionType()
}
this.infoConnection.next(this.info);
}, 3000);
}
}
isConnected() {
if (this.platform.is("cordova")) {
let hasConnection = this.network.type == "none" || this.network.type == 'unknown' ? false : true;
return hasConnection;
} else {
return true;
}
}
getConnectionType() {
if (this.platform.is("cordova")) {
return this.network.type;
} else {
return true
}
}
And try to connect and disconnect you phone to test