在Angular中的Firebase CRUD请求上显示加载栏

时间:2019-05-01 15:15:49

标签: angular firebase

我已阅读到有ngx-progressbar可以在有任何http请求时自动显示进度栏。我想知道从Firebase创建,读取,更新或删除数据时,Angular中是否有任何库或某种方式显示进度条。

我已经显示了加载指示器,但是感觉不太好。我只是在开始处理过程时给指标标签赋予true条件,如果过程完成或失败,则给false值。有时,当数据没有完全显示在页面上时,指示器会消失。

有任何提示吗?

1 个答案:

答案 0 :(得分:0)

实现加载栏的最佳方法是使用INTERCEPTOR。

app.module.ts

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LoaderInterceptorService } from './_services/loader-interceptor.service';
...
providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: LoaderInterceptorService,
    multi: true
  }
]

LoaderInterceptorService

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, pipe } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LoaderService } from '../_services/loader.service';
@Injectable({
  providedIn: 'root'
})
export class LoaderInterceptorService implements HttpInterceptor {
  constructor(private loaderService: LoaderService) { }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.showLoader();
    return next.handle(req).pipe(tap((event: HttpEvent<any>) => { 
      if (event instanceof HttpResponse) {
        this.onEnd();
      }
    },
      (err: any) => {
        this.onEnd();
    }));
  }
  private onEnd(): void {
    this.hideLoader();
  }
  private showLoader(): void {
    this.loaderService.show();
  }
  private hideLoader(): void {
    this.loaderService.hide();
  }
}

Documentaion Read more