在拦截器下面尝试
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { finalize } from 'rxjs/operators';
@Injectable()
export class HttpRequestsInterceptor implements HttpInterceptor {
requestQueue = [];
reqCount: number = 0;
reqFlag: boolean = false;
prevCount: number = 0;
obsIntrReq: any;
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
this.prevCount++;
if (this.prevCount >= 4) {
this.requestQueue.push(req);
this.obsIntrReq = Observable.interval(1000).do(() => {
if (this.reqFlag) {
this.requestQueue.splice(0, 1);
return next.handle(this.requestQueue[0]);
}
})
.switchMap(() => this.intervalPreviewChecking(this.reqCount, this.requestQueue.length))
.subscribe(() => { });
} else {
return next.handle(req).pipe(
finalize(() => {
this.prevCount--;
})
);
}
}
intervalPreviewChecking(rCount, requestQueueLength) {
if (requestQueueLength == 0) {
this.prevCount = 0;
this.reqFlag = false;
this.obsIntrReq.unsubscribe();
return this.obsIntrReq = null;
}
if (this.prevCount < 4) {
this.reqFlag = true;
return Observable.of(true);
}
this.reqFlag = false;
return Observable.of(false);
}
}
答案 0 :(得分:1)
每次HTTP调用都会调用拦截器。
如果我必须优先考虑我的电话,我不会在拦截器中执行,而是在我的功能中。
这就是我要做的事情(order =请求的优先级)。
const calls: {order: number, call: any}[] = [];
calls.push({order: 0, call: this.myService.makeCall(0) });
calls.push({order: 1, call: this.myService.makeCall(1) });
// etc.
const orderedCalls = calls.sort((a, b) => a.order - b.order).map(call => call.call);
Observable.forkJoin(orderedCalls);