在 Angular 中组合不重复的数组

Combining Arrays Without Duplicates in Angular

两个不同API的数据如Array1和Array2


数组 1=

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


数组 2=

[{"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" }]
const expected = [...array1, ...array2];

您可以选择使用 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 => {
 ...
})

您可以使用以下内容:

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

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

希望对您有所帮助!