【问题标题】:how to call multiple request in angular and get result together?如何以角度调用多个请求并一起获得结果?
【发布时间】:2018-07-08 00:51:01
【问题描述】:

我正在尝试在角度使用forkJoin 来异步处理多个请求并一起获取数据。我确实喜欢这样,但遇到了错误

这是我的代码

https://stackblitz.com/edit/angular-3jpqrc?file=src%2Fapp%2Fapp.component.ts

(此请求不适用于 https http://api.mathjs.org/v4/?expr=

服务代码

getcalculation(n:number){
    const url = 'http://api.mathjs.org/v4/?expr='+n+'*'+n;
    return this.http.get(url);
  }

组件代码

ngOnInit(){
    this.showAddButton = true;

    for(let i =0;i <this.item.length;i++){
      this.allSubScription$.push(this.dataservice.getcalculation(i));
    }

    forkJoin(this.allSubScription$).subscribe((result)=>{
      console.log(result)
    },(err)=>{
      console.log(err)
    })

  }

在本地,我收到此错误

【问题讨论】:

  • 我收到此错误cannot load http://api.mathjs.org/v4/?expr=2*2. Failed to start loading.was loaded over HTTPS, but requested an insecure XMLHttpRequest endpointThis request has been blocked; the content must be served over HTTPS. 似乎您的问题在服务器端,您是否遇到同样的错误?
  • 正如我已经提到的,它不适用于https
  • 在你的 stackBlitz 中,忘记 {headers:...}。只需 fetchDataThroughPromise(){ return this.http.get('restcountries.eu/rest/v2/all'); },看看你的 stackbilz 在stackblitz.com/edit/angular-waarr2

标签: javascript angular


【解决方案1】:

实现以下代码,只将allSubScription$ 数组添加到forkJoin 中,并且通过使用订阅,响应将是每个api 请求的数组。

 for(let i =0;i <this.item.length;i++){
      this.allSubScription$.push(this.dataservice.getcalculation(i));
    }

    forkJoin(
        this.allSubScription$
      ).subscribe((res) => {
        console.log(res[0]);
        console.log(res[1]);
        console.log(res[2]);
      }) 

我在运行 api url 时遇到问题,我只是强制响应模拟 api 响应。 demo

【讨论】:

  • 任何 api 失败时会发生什么
  • 所有forkjoin失败
猜你喜欢
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 2019-10-14
  • 2017-06-29
  • 1970-01-01
相关资源
最近更新 更多