Angular Async HTTP 请求不是异步发送的

标签 angular angular-httpclient

基本上我的问题是 - 我有 6 个不同的端点返回不同的数字 - 我希望能够异步发送 6 个请求,但使用 chrome 工具我发现它们按顺序运行而不是异步。

  ngOnInit() {
    private readonly TEMP_URL: string = 'https://www.random.org/integers/?num=1&min=1&max=100000&col=1&base=10&format=plain&rnd=new';
    const result1 = this.http.get<Number>(this.TEMP_URL);
    const result2 = this.http.get<Number>(this.TEMP_URL);
    const result3 = this.http.get<Number>(this.TEMP_URL);
    const result4 = this.http.get<Number>(this.TEMP_URL);
    const result5 = this.http.get<Number>(this.TEMP_URL);
    const result6 = this.http.get<Number>(this.TEMP_URL);
    const result7 = this.http.get<Number>(this.TEMP_URL);


    forkJoin(result1,result2,result3,result4,result5,result6,result7).subscribe(results  => {
                    this.retVal0= results[0];
                    this.retVal1 = results[1];
                    this.retVal2 = results[2];
                    this.retVal3= results[3];
                    this.retVal4= results[4];
                    this.retVal5= results[5];
                    this.retVal6= results[6];
                    this.retVal7= results[7];
            });
  };

enter image description here

最佳答案

在您的示例中,您多次请求相同的资源。

Chrome 缓存响应并使用缓存锁定机制,在发送对同一资源的下一个请求之前检查缓存。

The cache implements a single writer - multiple reader lock so that only one network request for the same resource is in flight at any given time.

Note that the existence of the cache lock means that no bandwidth is wasted re-fetching the same resource simultaneously. On the other hand, it forces requests to wait until a previous request finishes downloading a resource (the Writer) before they can start reading from it, which is particularly troublesome for long lived requests. Simply bypassing the cache for subsequent requests is not a viable solution as it will introduce consistency problems when a renderer experiences the effect of going back in time, as in receiving a version of the resource that is older than a version that it already received (but which skipped the browser cache).

https://www.chromium.org/developers/design-documents/network-stack/http-cache

如果您在开发者工具中禁用缓存,您应该会看到同时发送的请求。

您还可以在每个 url 的查询字符串中添加一些唯一的数字:

this.TEMP_URL + '?unique=<yourUniqueNumber>'

关于Angular Async HTTP 请求不是异步发送的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57377893/

相关文章:

javascript - 动态创建的元素上的 addEventListener 不起作用

angular - 在 Ngrx-nx Monorepo 中管理共享样式和 Assets

Angular 6 : HttpClient Get JSON File 404 Error

node.js - 如何在 Angular 应用程序中显示 Node js api 错误

Angular http请求可观察到的错误没有捕获错误?

javascript - 在 Azure 中部署 Angular 6

android - 这是库导入问题吗?抱歉 Google Play 商店,但我的应用不会有意访问麦克风或摄像头

angular - 如果Angular 2中没有数据字段,如何不出错

angular - 加载动态响应表单,不等待http调用完成

javascript - 使用 StreamSaver.js 流式传输大型 blob 文件