简体   繁体   中英

Ionic is possible to use LoadingController from external?

In my page I implemented the ionic LoadingController. To show loading dialog I make a method:

  public presentLoading(text: string, timeout: number) {
    if (!this.loading) {
      this.loading = this.loadingCtrl.create({
        content: text,
        dismissOnPageChange: true
      });
      this.loading.present();
      setTimeout(() => {
        this.closeLoading();
      }, timeout);
    }
  }

Now it is good, but I also want loading dialog in other pages, but I don`t want to duplicate the code and write again in other pages. I think making a static method which look like this:

public static presentLoading(loading: Loading, loadingCtrl: LoadingController, text: string, timeout: number) 

is ugly. Or the other way:

public loading: Loading

constructor(public loadingCtrl: LoadingController) { }

public presentLoading(text: string, timeout: number) { ... }

Is any other way to create MyLoadingController and instatiate it somehow and inject it in my page?

  • Create a new service called MyLoadingController
  • Inject loading controller into it constructor(private loadingCtrl: LoadingController) { }
  • Add your method in there
  • Inject new servive where you want to use

Finally I do it. I created CommonLoadingController which extends LoadingController and I added my methods there, and I add it to app.module.ts as a provider. Now I can use it anywhere in constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM