【问题标题】:Combine requests in series - Angular 7组合请求系列 - Angular 7
【发布时间】:2018-12-13 10:57:17
【问题描述】:

我正在尝试将几个请求串联起来,例如forkJoin,但请求不是并行请求的。到目前为止,这是我所拥有的:

let nodeDetails = this.http.get('node/1/')
let nodeParents = this.http.get('nodeParents/1/')
let nodeTree = this.http.get('nodeTree/1/')
let nodeUsers = this.http.get('nodeUsers/1/')
let nodeDocuments = this.http.get('nodeDocuments/1/')
var requests = [nodeDetails, nodeParents, nodeTree, nodeUsers, nodeDocuments]
forkJoin(requests)
  .subscribe(responses => {
    // List of all responses from all of the requests
    console.log(responses)
  })

我在某处读到 concat 可以与 toArray 结合使用,但这显然在最近的 rxjs 更新中被删除了。目前有没有办法做到这一点?

EDIT - 最终目标类似于this answer。该答案中的代码不再适用于 Angular 7 和 Rxjs 6.2.2。

【问题讨论】:

  • 所以你可以使用merge 或 [concat] (learnrxjs.io/operators/combination/concat.html) 取决于你对维护秩序的要求(或不)。
  • 只要使用concat
  • 所以我又通读了concatmerge 的文档,这就是问题所在。我需要单个数组中的响应 - 我不想在每个响应到达时订阅它。

标签: angular rxjs angular7 rxjs6


【解决方案1】:

这就是最终的工作:

import { toArray } from 'rxjs/operators';
import { concat } from 'rxjs';

let nodeDetails = this.http.get('node/1/')
let nodeParents = this.http.get('nodeParents/1/')
let nodeTree = this.http.get('nodeTree/1/')
let nodeUsers = this.http.get('nodeUsers/1/')
let nodeDocuments = this.http.get('nodeDocuments/1/')
const requests = concat(nodeDetails, nodeParents, nodeTree, nodeUsers, nodeDocuments)

requests
    .pipe(toArray())
    .subscribe(responses => {
        // Array of responses
    })

toArray() 运算符等待所有响应 - 按照concat 中提供的顺序。

【讨论】:

    【解决方案2】:

    您可以使用 Rxj6 中的concat。 Tyry 类似的东西:

    //  RxJS v6+
    import {concat} from 'rxjs';
    
    let nodeDetails = this.http.get('node/1/')
    let nodeParents = this.http.get('nodeParents/1/')
    let nodeTree = this.http.get('nodeTree/1/')
    let nodeUsers = this.http.get('nodeUsers/1/')
    let nodeDocuments = this.http.get('nodeDocuments/1/')
    
    const requests = concat(nodeDetails, nodeParents, nodeTree, nodeUsers, nodeDocuments)
    

    forkjoin 用于并行或 Rxjs 运算符,如 concatMap 用于非并行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 2011-07-10
      相关资源
      最近更新 更多