每个HTTP请求的Angular show Spinner,只需很少的代码更改 [英] Angular show spinner for every HTTP request with very less code changes

查看:44
本文介绍了每个HTTP请求的Angular show Spinner,只需很少的代码更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究现有的Angular应用程序.版本是Angular 4.

I am working on an existing Angular application. The version is Angular 4.

该应用程序通过许多组件对REST API进行HTTP调用.

The application makes HTTP calls to a REST API from lot of various components.

我想为每个HTTP请求显示一个自定义微调器.由于这是一个现有应用程序,因此在很多地方都可以调用REST API.而且在每个地方更改代码都不是可行的选择.

I want to show a custom spinner for every HTTP request. Since this is an existing application, there are lot of places where calls to REST API are made. And changing code one at every places is not a feasible option.

我想实现一个抽象的解决方案来解决这个问题.

I would like to implement an abstract solution which would solve this problem.

请建议是否有任何选择.

Please suggest if any options.

推荐答案

@jornare在他的解决方案中有个好主意.他正在处理多个请求的案件.但是,可以编写更简单的代码,而无需创建新的可观察到的请求并将请求存储在内存中.下面的代码还将RxJS 6与可管道运算符一起使用:

@jornare has a good idea in his solution. He's handling the case for multiple requests. However, the code could be written simpler, without creating new observable and storing requests in memory. Below code also uses RxJS 6 with pipeable operators:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpInterceptor,
  HttpResponse
} from '@angular/common/http';
import { finalize } from 'rxjs/operators';
import { LoadingService } from '@app/services/loading.service';
import { of } from 'rxjs';

@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
  private totalRequests = 0;

  constructor(private loadingService: LoadingService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    this.totalRequests++;
    this.loadingService.setLoading(true);

    return next.handle(request).pipe(
      finalize(res => {
        this.totalRequests--;
        if (this.totalRequests === 0) {
          this.loadingService.setLoading(false);
        }
      })
    );
  }
}

将此拦截器服务添加到您的模块提供程序中:

Add this interceptor service into your module providers:

@NgModule({
  // ...
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true }
  ]
})
export class AppModule { }

这篇关于每个HTTP请求的Angular show Spinner,只需很少的代码更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆