合并两个单独的http [关闭]数组

问题描述 投票:0回答:3

[两个不同的API的数据就像Array1和Array2

Array1 =

[{"ID" : 1  ,"Name": "abc" , "FamilyName" , "Grimes" },{"ID" : 2 ,"Name": "bcd" , "FamilyName" , "Grimes" }]

Array2 =

[{"ID" : 3  ,"Name": "efc" , "FamilyName" , "Grimes" },{"ID" : 4 ,"Name": "hij" , "FamilyName" , "Grimes" }]

预期输出:

 [{"ID" : 1  ,"Name": "abc" , "FamilyName" , "Grimes" },
  {"ID" : 2 ,"Name": "bcd" , "FamilyName" , "Grimes" },
  {"ID" : 3  ,"Name": "efc" , "FamilyName" , "Grimes" },
  {"ID" : 4 ,"Name": "hij" , "FamilyName" , "Grimes" }]
javascript arrays angular typescript angular9
3个回答
4
投票
const expected = [...array1, ...array2];

1
投票

您可以选择使用forkJoin:

const books = this.http.getbooks();
const authors = this.http.getauthors();

forkJoin([books, authors]).subscribe(response => {
 // response[0] will be req1 response
 // response[1] will be req2 response
})

评论中提到的另一个选项是使用CombineLatest:

combineLatest(books, authors).subscribe(response => {
 ...
})

0
投票

您可以使用以下内容:

combineLatest(
    observableAPI1,
    observableAPI2
)
    .pipe(take(1))
    .subscribe(([array1, array2]) => {
        const combinedArray = [...array1, ...array2];
    });

另外,我真的建议您使用类型。

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.