I have exact same requirement as mentioned in Add queueing to angulars $http service but need implementation in Angular 4.3 or 5 using the HttpInterceptor from
You can do this relatively easily. A naive example follows bellow.
It lacks typing etc, it's not elaborate, it has a few weak points, and it would be better to extract the queueing part and http-requesting part into different services or classes, but this should get you started.
interface PendingRequest {
url: string;
method: string;
options: any;
subscription: Observable;
}
@Injectable()
export class BackendService {
// This is your private requests queue emitter.
private requests$: Subject = new Subject();
private queue: PendingRequest[] = [];
constructor(private http: HttpClient) {
// subscribe to that queue up there
this.requests$.subscribe(request => this.execute(request));
}
// This is your public API - you can extend it to get/post/put or specific
// endpoints like 'getUserProfile()' etc.
invoke(url, method, options) {
return this.addRequestToQueue(url, method, params, options);
}
private execute(requestData) {
const req = this.httpClient.request(requestData.method, requestData.url, requestData.options)
// as a last step, invoke next request if any
.finally(() => this.startNextRequest());
const sub = requestData.subscription;
sub.switchMap(req);
}
private addRequestToQueue(url, method, options) {
const sub = new Subject();
const request = new PendingRequest(url, method, options, sub)
// if there are no pending req's, execute immediately.
if (this.queue.length === 0) {
this.requests$.next(request);
} else {
// otherwise put it to queue.
this.queue.push(request);
}
return sub;
}
private startNextRequest() {
// get next request, if any.
if (this.queue.length) {
this.execute(this.queue.shift());
}
}
}