<ion-content padding no-bounce>
<!--Se muestra si no hay conexion a internet.-->
<div *ngIf="!a">
<p padding>Es necesario estar conectado a Internet para cargar el listado de centros de urgencias. Por favor, conectese a una red WiFi o active sus datos.</p>
</div>
</ion-content>
.ts
...
import { Network } from '@ionic-native/network';
...
a: boolean;
constructor(private ngZone: NgZone, public navCtrl: NavController, public network: Network) {
this.a = true
}
ionViewDidLoad() {
this.comprobarConexionInternet();
}
comprobarConexionInternet(): void {
if (this.network.type === 'none') {
this.a = false;
this.network.onConnect().subscribe(() => { //nos ponemos a observar si se enciende la conexion a internet (si se activa se entra al interior)
this.a = true;
});
}
}
If I execute this piece of code, the content from the .html will show if I’m not connected to the Internet when I open the page. But if I start listening for Internet connection doing this.network.onConnect().subscribe(), the variable a will be set to true automatically when I get connected (already tested with console.log), but the message from the .html is still showing.
However, if I replace that piece of code for:
this.network.onConnect().subscribe(() => { //nos ponemos a observar si se enciende la conexion a internet (si se activa se entra al interior)
this.ngZone.run(() => {
this.a = true;
});
});
It works perfectly. I’d like to know why is this and what causes it.
this.network.onConnect().subscribe(() => { //nos ponemos a observar si se enciende la conexion a internet (si se activa se entra al interior)
this.ngZone.run(() => {
this.a = true;
});
});
And this doesn’t work:
comprobarConexionInternet(): void {
if (this.network.type === 'none') {
this.a = false;
this.network.onConnect().subscribe(() => { //nos ponemos a observar si se enciende la conexion a internet (si se activa se entra al interior)
this.a = true;
});
}
}
Using NgZone.run() makes it work.
I just wanna know why. What NgZone.run() does and why it doesn’t work without it.
Yeah, I understood, so please try my code, if it works, it’s just the ionViewDidLoad clear it context when all sync code is executed.
Then your async code is returned in another zone that the Angular view zone.
I did debug but can’t find out what goes on since everything works as it’s supposed to but it doesn’t work without the Ngzone stuff.
The this.network.type is just the Network plugin, if there is conection (none) it gets into the if and starts listening (waiting) for a conection with the .onChange().subscribe() and when the device is connected to the Internet it gets inside the code from the subscribe.
Okay just wanted to make sure the basics were already tested before digging deeper. So the simple answer is that the network connect observable updates outside of angular zone.
You can see this by just logging out a simple test.