问题
I'm looking for ionic2 best practice to show loadings, alerts and console logs..
so instead of repeat the code below in each page so I can call it once.
For example code to show loading:
showLoading() {
this.loading = this.loadingCtrl.create({
content: ''
});
this.loading.present();
}
Is it the best practice to create a provider, and show the loading from the last? or the provider doesn't support loading or something similar ?
Thanks.
回答1:
I usually create a lib folder (or module if you want). Then, I create some providers. For alert, you can create a provider:
import { Injectable } from '@angular/core';
import { AlertController } from 'ionic-angular';
@Injectable()
export class Alert {
constructor(
public alertCtrl: AlertController
) {}
show(title: string, subTitle: string, buttons: Array<string>): void{
let alert = this.alertCtrl.create({
title: title,
subTitle: subTitle,
buttons: buttons
});
alert.present();
}
}
Or for loading for example:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { LoadingController } from 'ionic-angular';
@Injectable()
export class Loader {
loader: any;
constructor(
public http: HttpClient,
public loadingCtrl: LoadingController
) {}
present(msg = `Please wait...`) {
this.loader = this.loadingCtrl.create({
content: "Please wait..."
});
this.loader.present();
}
dismiss() {
this.loader.dismiss();
}
}
And then, You can reuse in any components with module path mapping for example:
import { Alert, Toast } from '@lib';
Is this a best practice ? Yes, I think. You write less code and yo can reuse your lib providers.
Hope I help!
回答2:
I usually create an UtilProvider and then I create a method to show a loading dialog, for example:
public getLoading(message?) {
if (!message) {
message = 'Loading...';
}
return this.loadCtrl.create({content: message});
}
You can add the time out or just return the create, call present() and then dismiss() after.
I think that use it to AlertController is not really good, cause you will not handle de buttons click
来源:https://stackoverflow.com/questions/49191016/what-is-the-ionic2-best-practice-to-show-loading-alerts-and-logs