问题描述如下:
- 两次服务调用 (
/api/postsomedata
) 和 (/api/postsomeotherdata
) - 按顺序调用这两个服务调用 100 次(尽管这两个服务调用彼此不依赖)
我使用嵌套的concatMap
想出了以下rxjs实现:
import { range } from 'rxjs/observable/range';
import { concatMap } from 'rxjs/operators';
import { tap } from 'rxjs/operators/tap';
@Component({
selector: 'app-flow',
templateUrl: './flow.component.html',
styleUrls: ['./flow.component.scss']
})
export class FlowComponent implements OnInit {
constructor(public dataCallService: DataCallService) { }
ngOnInit() {
range(1, 100).pipe(
tap((d) => console.log(d)),
concatMap(() => this.dataCallService.firstAPI(data1).pipe(
concatMap(() => this.dataCallService.secondAPI(data2))
))
).subscribe(res => {
console.log(res)
});
}
}
虽然这工作正常;我使用的 tap
运算符立即发出 1 到 100 的值。我不确定它的做法是否正确。
有没有更好的方法来实现相同的目标?
最佳答案
为了链接请求,它应该类似于:
Observable.range(1, 100).map(i =>
this.dataCallService.firstAPI(data1)
.concatMap(() => this.dataCallService.secondAPI(data2))
})
.concatAll()
.subscribe(res => {});
请求可观察量可以通过 Angular 中的 Promise 方便地处理,因为 Http
和 HttpClient
都会产生具有单个值的完整可观察量。
除非请求可观察量应该在请求中间中止或与其他不完整/多值可观察量一起通过管道传输,否则切换到 promise 可能是有益的。
这会产生非常简单的async
函数,其中Promise.all
用于可以并行执行的请求:
async ngOnInit() {
try {
for (let i = 0; i < 100; i++) {
const [result1, result2] = await Promise.all([
this.dataCallService.firstAPI(data1).toPromise(),
this.dataCallService.secondAPI(data2).toPromise()
]);
}
} catch (err) { ... }
}
或系列:
async ngOnInit() {
try {
for (let i = 0; i < 100; i++) {
const result1 = await this.dataCallService.firstAPI(data1).toPromise();
const result2 = await this.dataCallService.secondAPI(data2).toPromise();
}
} catch (err) { ... }
}
关于angular - 调用顺序 HTTP 请求 100 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49829075/