Angular 2自定义Http服务(每次请求)

时间:2017-02-11 11:50:34

标签: javascript http angular angular2-services

我想要实现的是以某种方式处理我正在制作的每个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访问它,并在需要更改时操纵何时显示加载程序。

1 个答案:

答案 0 :(得分:4)

@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));
  }  
}

如果你不关心有多少未完成的请求,但就是否有任何

@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));
      }
    })
  }  
}