Add queueing to angulars $http service

前端 未结 6 1469
迷失自我
迷失自我 2020-12-07 17:24

I have a very quirky api that can only handle a single request at a time. Therefore, I need to ensure that every time a request is made, it goes into a queue, and that queue

6条回答
  •  暖寄归人
    2020-12-07 17:48

    If someone need solution to sequential http calls (as mentioned by OP) in Angular 5 then following is the solution:

        import { Injectable } from '@angular/core';
        import { Response } from '@angular/http';
        import { HttpClient } from '@angular/common/http';
        import { Observable } from 'rxjs/Observable';
        import { Subject } from 'rxjs/Subject'
    
        export class PendingRequest {
          url: string;
          method: string;
          options: any;
          subscription: Subject;
    
          constructor(url: string, method: string, options: any, subscription: Subject) {
            this.url = url;
            this.method = method;
            this.options = options;
            this.subscription = subscription;
          }
        }
    
        @Injectable()
        export class BackendService {
          private requests$ = new Subject();
          private queue: PendingRequest[] = [];
    
          constructor(private httpClient: HttpClient) {
            this.requests$.subscribe(request => this.execute(request));
          }
    
          /** Call this method to add your http request to queue */
          invoke(url, method, params, options) {
            return this.addRequestToQueue(url, method, params, options);
          }
    
          private execute(requestData) {
            //One can enhance below method to fire post/put as well. (somehow .finally is not working for me)
            const req = this.httpClient.get(requestData.url)
              .subscribe(res => {
                const sub = requestData.subscription;
                sub.next(res);
                this.queue.shift();
                this.startNextRequest();
              });
          }
    
          private addRequestToQueue(url, method, params, options) {
            const sub = new Subject();
            const request = new PendingRequest(url, method, options, sub);
    
            this.queue.push(request);
            if (this.queue.length === 1) {
              this.startNextRequest();
            }
            return sub;
          }
    
          private startNextRequest() {
            // get next request, if any.
            if (this.queue.length > 0) {
              this.execute(this.queue[0]);
            }
          }
        }
    

    In case of someone wants to look at working plunker then here is the working plunker.

提交回复
热议问题