Angular 2 个自定义 Http 服务(针对每个请求)

Angular 2 custom Http service ( on every request )

我想要实现的是以某种方式处理我正在发出的每个 Http 请求,并在每个请求上更改我的变量状态。所以我制作了包装 Angular 2 Http 服务的自定义 Http 服务:

import {Injectable} from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import {Observable} from "rxjs";
import 'rxjs/add/operator/map';

@Injectable()
export class HttpClientService {
  public isLoading: boolean = false;

  constructor(private http: Http) {}

  get(url) {
    let headers = new Headers();
    this.isLoadingHttp(true);
    return this.http.get(url, {
      headers: headers
    });
  }  

  isLoadingHttp( state: boolean ): void {
    this.isLoading = state;
  }
}

所以我有isLoading变量isLoadingHttp函数

第一个问题 - 基本上,在 GET 方法开始时,我将变量设置为 true,但我怎么知道何时发出请求和响应准备好?

第二个问题:我需要制作isLoading和Observable吗?我想从我的 AppComponent 访问它,并在它发生变化时控制何时显示加载器。

@Injectable()
export class HttpClientService {
  private _isLoading: number = 0;

  public get isLoading () {
    return this._isLoading;
  }

  constructor(private http: Http) {}

  get(url) {
    let headers = new Headers();
    this._isLoading++;
    return this.http.get(url, {
      headers: headers
    })
    .finally(_ => this._isLoading--);
  }  
}

一次可以有多个活动请求。

需要像导入任何其他运算符一样导入 finally 运算符。

@Injectable()
export class HttpClientService {
  private requestCounter: number = 0;
  private isLoading: Subject<number> = new BehaviorSubject<number>(requestCounter);
  public readonly isLoading$:Observable<number> = this._isLoading.asObservable().share();

  constructor(private http: Http) {}

  get(url) {
    let headers = new Headers();
    this.isLoading.next(++this.requestCounter);
    return this.http.get(url, {
      headers: headers
    })
    .finally(_ => this.isLoading.next(--this.requestCounter));
  }  
}

of 如果您不关心有多少未完成的请求,但只要有就可以了

@Injectable()
export class HttpClientService {
  private requestCounter: number = 0;
  private isLoading: Subject<boolean> = new BehaviorSubject<boolean>(false);
  public readonly isLoading$:Observable<boolean> = this._isLoading.asObservable().share();

  constructor(private http: Http) {}

  get(url) {
    let headers = new Headers();

    this.requestCounter++;
    if(this.requestCounter == 1) {
      this.isLoading.next(true);
    }
    return this.http.get(url, {
      headers: headers
    })
    .finally(_ => {
      this.requestCounter--;
      if(this.requestCounter == 0) {
        this.isLoading.next(false));
      }
    })
  }  
}