使用 'HttpClient' Angular 8 的多个呼叫

Multi calls using 'HttpClient' Angular 8

我想使用 'HttpClient' 进行多路通话。类似于我以前与 axios 一起使用的东西。

在 Vue 中使用 axios:

return axios.all([
      axios.get('/friends/name'),
      axios.get('/family/name'),
      axios.get('/collegue/name'),
])

尝试 angular:

return this.http.all([
      this.http.get('/friends/name'),
      this.http.get('/family/name'),
      this.http.get('/collegue/name'),
])

错误 TS2339:属性 'all' 在类型 'HttpClient'

上不存在

像这样使用 forkJoin 试试:

 ngOnInit() {    
    const request1 = this.http.get('/friends/name');
    const request2 = this.http.get('/family/name');
    const request3 = this.http.get('/collegue/name');

    forkJoin([request1, request2, request3]).subscribe(data => {
      this.response1 = data[0];
      this.response2 = data[1];
      this.response3 = data[2];
    });
  }

您必须使用 forkJoin 运算符并按如下方式订阅数据

forkJoin([
  this.http.get('/friends/name'),
  this.http.get('/family/name'),
  this.http.get('/collegue/name'),
 ])

当使用 HttpClient 发出请求时,它将 return 一个 rxjs Observable,您必须订阅它才能发出请求。根据您的用例,您应该查看 rxjs 中的 these 运算符之一。

例如,您可以像这样使用 merge 运算符:

const requests = merge(
    this.http.get('/friends/name'),
    this.http.get('/family/name'),
    this.http.get('/collegue/name')
);
requests.subscribe(console.log); // Executes the requests and logs them as they complete