我想要实现的是以某种方式处理我发出的每个 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
variable 和 isLoadingHttp
function。
第一个问题 - 基本上,在 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));
}
}
如果你不关心有多少未完成的请求,但如果有的话就可以
@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));
}
})
}
}
关于javascript - Angular 2 自定义 Http 服务(针对每个请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42175513/