如何在每个服务调用中以角度/离子显示/隐藏加载程序?

时间:2019-02-27 09:23:28

标签: angular ionic3 provider

我有一个提供程序,其中有许多函数,在ionic中执行任何函数调用之前,有任何方法可以执行一个函数。 这是我的代码,我想在每个HTTP调用之前执行一个加载器函数 无需多次调用函数即可轻松实现

 @Injectable()
  export class HttpProvider {
    BASEURL: string = 'https://www.ngrok.io';
    constructor(public http: HttpClient) {
      console.log('Hello HttpProvider Provider');
    }

    getCustomerInfo(customer_mobile) {
      return this.http.post(this.BASEURL + '/customer/get', {
        customer_mobile,
      });
    }

    addNewCustomer(customerInfo) {
      return this.http.post(this.BASEURL + '/customer/save', customerInfo);
    }
    updateCustomer(customerInfo) {
      return this.http.post(this.BASEURL + '/customer/update', customerInfo);
    }

    getVendorList(filterObject) {
      return this.http.post(this.BASEURL + '/getvendorlist', filterObject);
    }

    getVendorInfo(vendor_id) {
      return this.http.post(this.BASEURL + '/getvendorinfo', {
        vendor_id,
      });
    }

    updateAddress(updatedAddress) {
      return this.http.post(
        this.BASEURL + '/customeraddress/update',
        updatedAddress
      );
    }
    addAddress(newAddress) {
      return this.http.post(this.BASEURL + '/customeraddress/save', newAddress);
    }

    addOrder(orderDetails) {
      return this.http.post(this.BASEURL + '/order/save', orderDetails);
    }

    deleteAddress(address_id) {
      return this.http.post(this.BASEURL + '/customeraddress/delete', {
        address_id,
      });
    }
    getOrderList(customer_id, date?) {
      return this.http.post(
        this.BASEURL + '/fetchallcustomerorders',
        requestBody
      );
    }
    addReview(review: { feedback: string; rating: string; order_id: string }) {
      return this.http.post(this.BASEURL + '/orderreview', review);
    }


  }

1 个答案:

答案 0 :(得分:4)

您可以使用HTTPInterceptors在每个服务调用中显示/隐藏加载程序。

本教程将帮助您实现这一目标:Show Loader on every service call in angular

您可以在intercept方法内显示加载程序,一旦响应到来就可以将其隐藏。

@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor(private loaderService: LoaderService) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.loaderService.show();

    return next
        .handle(req)
        .do(event => {
            if (event instanceof HttpResponse) {

                this.loaderService.hide();
            }
        });
  }