Ionic 4: “Loading Controller” dismiss() is called before present() which will keep spinner without dismissing

前端 未结 20 2285
逝去的感伤
逝去的感伤 2020-12-08 01:06

I used \"Ionic Loading Controller\" to show a spinner until the data is retrieved then it calls \"dismiss()\" to dismissed it. it works fine, but sometimes when the app alre

20条回答
  •  猫巷女王i
    2020-12-08 01:34

    Here's how I've solved the same issue in my project. I use this service in the HTTP Interceptor to show the loader for all the REST API calls inside my app.

    loading.service.ts

    import {Injectable} from '@angular/core';
    import {LoadingController} from '@ionic/angular';
    
    @Injectable({
      providedIn: 'root'
    })
    export class LoadingService {
      constructor(public loadingController: LoadingController) {
      }
    
      async present(options: object) {
        // Dismiss all pending loaders before creating the new one
        await this.dismiss();
    
        await this.loadingController
          .create(options)
          .then(res => {
            res.present();
          });
      }
    
      /**
       * Dismiss all the pending loaders, if any
       */
      async dismiss() {
        while (await this.loadingController.getTop() !== undefined) {
          await this.loadingController.dismiss();
        }
      }
    }
    

    In the original question context this could be used like below:

    ...
    import {LoadingService} from '/path/to/loading.service';
    ...
    customer: any;
    
    constructor(public loadingService: LoadingService, private customerService: CustomerService)
    
    ngOnInit() {
      this.loadingService.present({
        message: 'wait. . .',
        duration: 5000
      });
      this.customerService.getCustomer('1')
      .subscribe(customer => {
        this.customer = customer;
        this.loadingService.dismiss();
      }
    }
    

提交回复
热议问题