如何在Angular 7中使用管道在http请求中强制执行序列

时间:2018-11-08 22:50:51

标签: angular http sequence angular7

我有一个组件,可以调用一些对不同URL的http请求。每个请求都是可观察的。

getIds():Observable<any[]> {
   return this.http
    .post(url1, '')
    .pipe(map(({ Ids}: any) => Ids.map(item => ({Id: item.Id }))));
    }

getNames(data: Names):Observable<any[]> {
   return this.http
    .post(url2,element)
    .pipe(map(({ Results }: any) => Results[0].map(item => ({id: item.ID, name: item.CVSS}))));
    }

我需要从组件中完成

ngOnInit() {
  this.Ids = this.getIds();
  Ids.forEach(function(element) 
     this.getNames();
}

有人可以告诉我如何执行此命令吗?

2 个答案:

答案 0 :(得分:0)

从RXJS导入switchMap

import { switchMap } from 'rxjs/operators'

然后通过管道将地图返回到可观察的

this.getIds().pipe(
  switchMap((id: string) => this.getNames(id))
).subscribe((response) -> {
  console.log(response)
})

答案 1 :(得分:0)

getIds返回一个ID数组,您想为每个ID创建一个Observable(getNames)。然后,您想将所有名称列表排列在一起。您可以通过多种方式执行此操作,但是我建议一种:

this.getIds().pipe(
  /*
   * mergeMap here will effectively flatten the inner Observable created by getNames.
   * This means that the next operator will get the *result* of the getNames Observable
   * rather than the Observable itself, so you don't need to subscribe to it explicitly.
   */
  mergeMap(id => this.getNames(id)),

  /*
   * This is optional. `names` is an array. `mergeMap` over an array emits each array element
   * individually. This simply flattens the collection of names arrays.
   */
  mergeMap(names => names),

  /**
   * This is also optional. It will emit the entire collection of results as an array once
   * all of the previous Observables have completed.
   */
  toArray()
)

您可以订阅由此创建的Observable以获得扁平化的名称列表。

我还建议,如果可能的话,您可以在服务中添加一个方法,该方法允许您检索所有名称,而不必先检索ID列表以及每个ID的每个名称。