angular interceptor trying to make a interceptor which queue the request of max request 10

68 Views Asked by At
# import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
# import { Injectable } from '@angular/core';
# import { Observable, interval } from 'rxjs';
# import { of } from 'rxjs/internal/observable/of';
# import { map } from 'rxjs/internal/operators/map';
# import { finalize, last, mapTo, mergeMap, takeWhile } from 'rxjs/operators';
# export const MAX_REQUESTS = 10;
# # @Injectable()
# export class SmartCountInterceptorService implements HttpInterceptor {
# private activeRequests = 0;
# intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
# Check if the maximum number of active requests has been reached
# if (this.activeRequests >= MAX_REQUESTS) {
# Wait for ongoing requests to complete before processing the new request
# return this.waitForActiveRequests().pipe(
# mergeMap(() => {
# Clone the request to prevent modification
# const clonedReq = req.clone();
# Increment the count of active requests
# this.activeRequests++;
# Handle the request
# return next.handle(clonedReq).pipe(
# finalize(() => {
# Decrement the count of active requests when the request completes
# this.activeRequests--;
# #             })
# #           );
# #         })
# #       );
# else {
# Clone the request to prevent modification
# const clonedReq = req.clone();
# Increment the count of active requests
# this.activeRequests++;
# Handle the request
# return next.handle(clonedReq).pipe(
# finalize(() => {
# Decrement the count of active requests when the request completes
# this.activeRequests--;
# #         }),
# mergeMap(event => {
# Wait for ongoing requests to complete before emitting the event
# return this.waitForActiveRequests().pipe(map(() => event));
# #         })
# #       );
# #     }
# #   }
# private waitForActiveRequests(): Observable<void> {
# if (this.activeRequests < MAX_REQUESTS) {
# If the maximum number of active requests has not been reached, return an empty observable
# return of(null);
# else {
# Otherwise, wait for all active requests to complete
# return interval(100).pipe(
# takeWhile(() => this.activeRequests > MAX_REQUESTS),
# last(),
# mapTo(null)
# #       );
# #     }
# #   }
# # }

This is my interceptor in which all the request are been intercepted, but few requests show error Empty error 'no elements in sequence'. I tried removing last() and used take 1 but still the issue persists.

I need to take care whatever b the request number it will first send 10 request at time and if response comes of any one or two accordingly the active request will be pushed

0

There are 0 best solutions below