angular - 在 Angular 6 中顺序执行 http 请求

标签 angular typescript angular6 observable

我需要依次向服务器发送多个HTTP PUT请求(下一个请求只有在完成上一个请求后才开始,请求的数量不固定)。 如果我使用下面的源代码,所有的请求都会被发送

 `listURL.forEach(url => {
    const req = new HttpRequest('PUT', url, formData, { reportProgress: true});
    httpClient.request(req).subscribe(event=>{});
  });`

有没有按顺序执行请求的方法?

最佳答案

您可以将 async/await 与 Promise 结合使用来简化此操作。使用 toPromise()

将 observable 转换为 promise
async doSomethingAsync() {
    for(let url of listURL) {
        const req = new HttpRequest('PUT', url, formData, { reportProgress: true});
        const result = await httpClient.request<ModelHere>(req).toPromise();
        // do something with result
    }
}

有关 async/await 的更多信息,另请参阅这个出色的答案并滚动到标题 ES2017+: Promises with async/await .

关于angular - 在 Angular 6 中顺序执行 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53654176/

相关文章:

css - Angular 2,媒体查询在与 [ngStyle] 指令结合使用时不起作用

javascript - 重用 Angular 和 html 的冗余函数

javascript - 使用非字母数字字符时如何使填充空格结果具有相似的长度?

javascript - typescript 错误 : Argument of type 'number' is not assignable to parameter of type 'Expected<Promise<number>>'

Angular6 - ngIf 不会破坏对象

angular - 错误 TS2563 : The containing function or module body is too large for control flow analysis

javascript - Angular 4 : Validators. 模式()不起作用

javascript - Angular 6 : Prevent Browser Tooltip to show HTML tags in "innerHtml"

javascript - 在窗口滚动时更改 Angular 2 中的组件样式?

javascript - 如何在父级中隐藏/显示 ContentChild