通过拦截HTTP请求(HTTPinterceptors)来创建一个常见的加载程序



我在离子3中创建一个公共加载器,但是由于手动使用loader.dismiss()

而存在问题

我打算只在Ionic中使用loaderCtrl在非常CC_2上创建加载程序,而是打算仅制作一个加载程序。我正在使用httpInterceptor,当请求截获时,我创建并呈现加载程序。我检查该事件是否为HttpRequest类型,如果是的,则将加载程序被解雇。

当仅在任何页面上提出http请求时,此请求是截获截止的,稍后将在获得响应时,将加载程序截获。

现在,如果在1页上提出了2个请求,则一扇门,找不到removeView 的错误

/loaderInterceptor.ts

@Injectable()
  export class HttpLoaderInterceptor implements HttpInterceptor {
  headersConfig: any;
  loader: any
  constructor(public loadingCtrl: LoadingController) { }
  intercept(req: HttpRequest<any>, next: HttpHandler): 
  Observable<HttpEvent<any>> {
    this.loader = this.loadingCtrl.create({
    content: "Please wait",
    });
   this.loader.present()

 return next.handle(req).pipe(tap((event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
      this.loader.dismiss();
  }
},
  (err: any) => {
      this.loader.dismiss();
       }));
 }
}

将解雇方法称为两次,因为获得了2个响应,并且第二次没有被解雇的装载机,因此我们会遇到错误。请帮助。

在我的想法中,加载条形理由之前的请求成功,因此我创建了一个服务来解决它。我的源代码如下:

import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';
@Injectable({
  providedIn: 'root'
})
export class LoadingService {
  private loaders = [];
  private badLoaders = 0;
  constructor(
      private loadingController: LoadingController
  ) {
  }
  async startLoading() {
      if (this.badLoaders > 0) {
          this.badLoaders --;
      } else {
          await this.loadingController.create({
              message: 'Loading ...',
          }).then(loader => {
              this.loaders.push(loader);
              loader.present().then(() => {
                  if (this.badLoaders > 0) {
                      this.badLoaders --;
                      this.endLoading();
                  }
              });
          });
      }
  }
  endLoading() {
      let loader = this.loaders.pop();
      if (loader) {
          loader.dismiss();
      } else {
          this.badLoaders ++;
      }
  }
}

您可以尝试一下,使用loadingService.startloading代替this.loadingCtrl.create和LoadingService.Endloading而不是this.loader.dismiss();

相关内容

最新更新