重复 http.post 指定次数(每次更改 URL)?

Repeating http.post a specified number of times (changing the URL each time)?

我想不出 repeat/loop Angular2(4) http.post 请求指定 (X) 次的正确方法。

让我举例说明我希望实现的目标。我有以下 http.post:

this.http.post(`http://url.com/param/name01`, dbJson, options)

我需要做的是使用单个可观察流 post 到 API X 次,每次更改名称参数。我不想像这样硬编码:

this.http.post(`http://url.com/param/name01`, body, options)
.switchMap(() => this.http.post(`http://url.com/param/name02`, body, options)
.switchMap(() => this.http.post(`http://url.com/param/name03`, body, options)

任何人都可以阐明使用 observables 获得我想要的结果的最佳方法吗?

提前致谢。

您可以通过使用 forkJoin 实现此目的,它会循环所有请求

myNameRequest(): Observable<any> {
 let requests: any[] = [];
 let names: string[] = ['name1', 'name2', 'name3'];
 return Observable.forkJoin(names.map(name => this.http.post(`http://url.com/param/${name}`, body, options)))
}

如果您必须在每个请求或所有请求后执行任何操作,您可以在 map/subscribe 中执行此操作,您可以在此处了解相关信息

https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs https://www.metaltoad.com/blog/angular-2-http-observables-and-concurrent-data-loading

如果您需要一个接一个地执行请求,请使用 concat。您可以使用参数创建一个可观察值数组,并使用扩展运算符将它们传递给 concat。

let names = ['name01', 'name02', 'name03'];

let obs$ 
    = names.map(name=>Rx.Observable.of('path' + name));

Rx.Observable.concat(...obs$)
  .subscribe(x=>console.log(x));