问题
I have this function that listen the internet connection
private verifyNetworkConnection() {
this.networkService
.isNetworkConnected
.pipe(distinctUntilChanged())
.subscribe(connected => {
if (connected) {
// do secret things
} else {
this.toast.create({
message: 'Sem conexão a internet',
showCloseButton: true,
duration: 2000,
cssClass: ToastClasses.ERROR
}).then((res) => res.present());
this.disconnectFromServices();
}
});
}
And in the else block, i need to show a Toast that says the user has no connection, but the toast doenst show, i read some topics saying that the ToastController is lazy loaded and cant load when there is no connection, is there anyway to Eager Load the component to show when there's no connection ??
回答1:
You can easily do it like so: i.e. create a service
network-state.service.ts
import { Injectable } from "@angular/core";
import { Network } from "@ionic-native/network/ngx";
import { Subscription } from "rxjs";
import { ShowToastService } from "./show-toast.service";
@Injectable({
providedIn: "root"
})
export class NetworkStateService {
private connectSubscription$: Subscription = null;
constructor(private network: Network,
private showToastService: ShowToastService) { }
WatchConnection() {
if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
this.connectSubscription$ = this.network.onDisconnect().subscribe(() => {
this.showToastService.showToast("Your internet seems to be down! Please check your network settings!",'danger');
if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
this.connectSubscription$ = this.network.onConnect().subscribe(() => {
setTimeout(async() => {
this.showToastService.toast.dismiss();
if (this.network.type === "wifi" || this.network.type === "4g" || this.network.type === "3g" || this.network.type === "2g" || this.network.type === "cellular" || this.network.type === "none") {
this.showToastService.showToast("Internet connection available!",'success');
this.WatchConnection();
}
}, 3000);
});
});
}
}
Then inject it like so:
app.component.ts
constructor(private networkStateService: NetworkStateService,){
this.initializeApp();
}
async initializeApp() {
await this.platform.ready();
this.statusBar.styleDefault();
this.splashScreen.hide();
if (this.platform.is("cordova")) {
this.networkStateService.WatchConnection();
}
}
Toast service is like so:
show-toast.service.ts
import { Injectable } from "@angular/core";
import { ToastController, Events } from "@ionic/angular";
@Injectable({
providedIn: "root"
})
export class ShowToastService {
toast: HTMLIonToastElement;
constructor(private toastCtrl: ToastController,
) { }
async showToast(message: string, color: string): Promise<void> {
const toast: HTMLIonToastElement = await this.toastCtrl.create({
message,
duration: 3000,
position: 'bottom',
color,
buttons: [
{
text: 'Ok',
handler: () => {
}
}
]
});
toast.present();
}
}
来源:https://stackoverflow.com/questions/59306362/eager-load-an-ionic-toast-controller