RxJS:将多个http请求组合成一个扁平的可观察数组



我遇到了一个问题,如何并行组合多个http get请求,并将其作为一个平面的、可观察的数组返回。

目前,我有一个方法returnNewCars(),它在发出一个http-get请求后返回Observable<ICar[]>——在方法returnAllCars()中,我想发出多个http-gete请求,但仍然返回Observable<ICar[]>

现在,returnNewCars()打印:

(2) [{…}, {…}]
0: {Make: "Honda", Model: "CRV", Year: "2021", Specifications: Array(5)}
1: {Make: "Toyota", Model: "Camry", Year: "2021", Specifications: Array(5)}
length: 2

我希望returnAllCars()以相同的格式打印,但要使用所有6项。

我遵循了关于forkJoin的RxJS文档,并试图在代码中反映它,然而,我不知道从哪里开始。

应用程序组件.ts

import { Component, OnInit } from '@angular/core';
import { CarsService } from './services/cars.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'AutoZone';
constructor(private carsService: CarsService){
}
ngOnInit(): void {
}

testConsole(){
this.carsService.returnNewCars().subscribe(newCars => console.log(newCars));
}
}

汽车服务.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from "@angular/core";
import { forkJoin, Observable } from 'rxjs';
import { concatMap, map, tap } from 'rxjs/operators';
import { ICar } from '../models/cars.model';
@Injectable({
providedIn: 'root'
})
export class CarsService{
carsURL = '/assets/cars.mock.json';
newCarsURL = '/assets/cars.new.mock.json';
preownedCarsURL = '/assets/cars.preowned.mock.json';
usedCarsURL = '/assets/cars.used.mock.json';
private newCars$: Observable<ICar[]>;
//Store all http get request to new, preowned, used
private allCars$: Observable<ICar[]>;
constructor(private http : HttpClient){
}

returnNewCars(): Observable<ICar[]>{
this.newCars$ = this.http.get<ICar[]>(this.newCarsURL);
return this.newCars$;
}
returnAllCars(): Observable<ICar[]>{
//How do I flatten to return Observable<ICar[]>?
forkJoin(
{
new: this.http.get<ICar[]>(this.newCarsURL),
preowned: this.http.get<ICar[]>(this.preownedCarsURL),
used: this.http.get<ICar[]>(this.usedCarsURL)
}
)

return null;
}
}

您只需添加一个.pipe(map(...))即可将3个单独的数组转换为一个数组。

我看不出有任何理由需要将对象传递给forkJoin,您可以简单地传递一个数组:

returnAllCars(): Observable<ICar[]>{
return forkJoin([
this.http.get<ICar[]>(this.newCarsURL),
this.http.get<ICar[]>(this.preownedCarsURL),
this.http.get<ICar[]>(this.usedCarsURL)
]).pipe(
map(([new, preowned, used]) => [...new, ...preowned, ...used])
);
}

另外,Observables是惰性的,所以没有必要用这样的方法来包装它们:

returnNewCars(): Observable<ICar[]>{
this.newCars$ = this.http.get<ICar[]>(this.newCarsURL);
return this.newCars$;
}

你可以简单地定义如下:

private newCars$ = this.http.get<ICar[]>(this.newCarsURL);

因此,在allCars()的情况下,您可以简单地执行:

private allCars$ = forkJoin([this.newCars$, this.preOwnedCars$, this.usedCars$])
.pipe(
map(([new, preowned, used]) => [...new, ...preowned, ...used])
);

我不知道为什么你需要这个逻辑来用一个方法获取所有的汽车,因为你应该调用一个api来分别获取三种汽车列表。不管怎样,我尝试了一种方法来获得All,正如你所期望的那样,并使用了forkJoin。

这是堆叠链路

相关内容