首页 > 解决方案 > 如何在Angular 7中使用管道强制http请求中的顺序

问题描述

我有一个组件可以调用一些对不同 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();
}

有人可以展示我如何执行此命令吗?

标签: angularhttpsequenceangular7

解决方案


从 RXJS 导入 switchMap

import { switchMap } from 'rxjs/operators'

然后通过管道传输到返回的 observable 上的地图

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


推荐阅读