Struggling with combining multiple http get requests simultaneously and returning them as a unified, observable array.
In my current setup, the method returnNewCars()
retrieves Observable<ICar[]>
by executing a single http get request. However, in the scenario of returnAllCars()
, I aim to perform multiple http get requests and still return Observable<ICar[]>
.
The output of returnNewCars()
looks like this:
(2) [{…}, {…}]
0: {Make: "Honda", Model: "CRV", Year: "2021", Specifications: Array(5)}
1: {Make: "Toyota", Model: "Camry", Year: "2021", Specifications: Array(5)}
length: 2
I hope for returnAllCars()
to display a similar structure but with all the 6 items included.
Following the guidance from RxJS documentation on forkJoin, I attempted to incorporate it into my code but am unsure of the next steps.
app.component.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));
}
}
cars.service.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;
}
}