Angular 8发出多个http请求并合并所有结果

时间:2019-10-29 07:48:36

标签: angular typescript rxjs angular8 fork-join

我正在尝试使用forkJoin执行多个http get请求,然后使用Angular 8将所有结果组合到一个简单的Array中。

问题是我最终得到一个数组数组...而不是一个字符串数组

下面的我的代码。所有端点都返回一个字符串列表。

autoCompleteValues: any;

ngOnInit() {

    let res1 = this.dataMessageService.getFoo1();
    let res2 = this.dataMessageService.getFoo2();
    let res3 = this.dataMessageService.getFoo3();
    let res4 = this.dataMessageService.getFoo4();
    let res5 = this.dataMessageService.getFoo5();

    forkJoin([res1, res2, res3, res4, res5]).subscribe(data => {

      this.autoCompleteValues = data;
      console.log(this.autoCompleteValues);
    });
}

我在做什么错?如何将所有结果组合成一个大数组?

5 个答案:

答案 0 :(得分:1)

您的代码正确,因为这是forkjoin的预期行为 您只需要将其映射一下

forkJoin([res1, res2, res3, res4, res5])
.pipe(map(data => data.reduce((result,arr)=>[...result,...arr],[])))
.subscribe(data =>{

  this.autoCompleteValues = data;
  console.log(this.autoCompleteValues);
});

答案 1 :(得分:1)

代替此:

forkJoin([res1, res2]).subscribe((data) => {
    console.log(data)
});

执行此操作:

forkJoin([res1, res2]).subscribe(([data1, data2]) => {
    console.log(data1)
    console.log(data2)
});

答案 2 :(得分:0)

您可以这样做

 forkJoin([res1, res2, res3, res4, res5])
.pipe(map([res1, res2, res3, res4, res5]) 
    => [...res1, ...res2, ...res3, ...res4, ...res5])).subscribe(data => {
    this.autoCompleteValues = data;
    console.log(this.autoCompleteValues);
});

确保也导入地图运算符

import { map } from "rxjs/operators";

答案 3 :(得分:0)

如果提供给forkJoin的任何内部可观察变量出错,则您将丢失将要或已经完成的任何其他可观察变量的值。

请参考以下链接:- https://www.learnrxjs.io/operators/combination/forkjoin.html

答案 4 :(得分:0)

app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { forkJoin } from 'rxjs/observable/forkJoin';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  response = [];
  constructor(public http: HttpClient) {
    const request1 = this.http.get('https://restcountries.eu/rest/v1/name/india');
    const request2 = this.http.get('https://restcountries.eu/rest/v1/name/us');
    const request3 = this.http.get('https://restcountries.eu/rest/v1/name/ame');
    const request4 = this.http.get('https://restcountries.eu/rest/v1/name/ja');

    const requestArray = [];
    requestArray.push(request1);
    requestArray.push(request2);
    requestArray.push(request3);
    requestArray.push(request4);

    forkJoin(requestArray).subscribe(results => {
      console.log(results);
      this.response = results;
    });
  }
}