将队列添加到Angular的HttpClient

希特什·谢卡达

我有与向angulars $ http服务添加队列中提到的完全相同的要求,但需要使用HttpInterceptorfrom来在Angular 4.3或5中实现@angular/common/http

我有一个非常古怪的API,它一次只能处理特定浏览器会话的单个请求。因此,我需要确保每次在同一会话中发出请求时,该请求都会进入队列,并且该队列一次执行一个请求,直到该请求为空。

希特什·谢卡达


@Zlatko建议使用正确的方法,尽管其中几乎没有逻辑和语法问题,但我已将其粘贴到工作代码下面进行了更正:

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<any>;

  constructor(url: string, method: string, options: any, subscription: Subject<any>) {
    this.url = url;
    this.method = method;
    this.options = options;
    this.subscription = subscription;
  }
}

@Injectable()
export class BackendService {
  private requests$ = new Subject<any>();
  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<any>();
    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]);
    }
  }
}

一个人可以通过以下方式使用/调用上述服务来进行HTTP调用(从任何其他组件或服务)(显然,您需要在组件中注入BackendService,例如在组件提供者中提及并在构造函数中进行定义):

    this.backendService.invoke('https://jsonplaceholder.typicode.com/posts', 'Get', null, null)
    .subscribe(
      result => {
        this.data = result;
      }
    );

如果有人想看工作的柱塞,那么这里就是工作的柱塞

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章