Imagine a scenario where there is a web service that returns basic data in the form of CustomerGroups:
{
0: {
Name: 'Group 1',
Customers: {
...
}
},
1: {
Name: 'Group 2',
Customers: {
...
}
}
}
...and another web-service that provides detailed customer data:
{
CustomerNo: 1,
Street: 'Test Street 123',
PostCode: '99999',
City: 'Blabla',
...
}
The goal is to combine the results of both services using ForkJoin within an Angular4 injectable service. However, encountering challenges when trying to retrieve specific details for each customer:
ReadAll(useCache?: boolean): Observable<ICustomerGroup[]> {
if (!this.customerGroupCache || !useCache) {
return this.http.get(this.urlGetAll)
.map((res: Response) => res.json())
.flatMap((customerGroups: any[]) => {
...
})
.catch((error: any) => Observable.throw(error.message || 'Server error'));
}
return Observable.of(this.customerGroupCache);
}
How can ForkJoin be utilized to iterate over each "CustomerGroup" and fetch detailed information for each "Customer"? Is it feasible to use "forEach" inside a "ForkJoin"?
The expected outcome after applying "ForkJoin" should resemble:
{
0: {
Name: 'Group 1',
Customers: {
0: {
CustomerNo: 1,
Name: 'Customer 1',
Street: 'Test Street 123',
PostCode: '99999',
City: 'Blabla'
},
...
}
}
...
}
Solution
As suggested by taras-d, incorporating mergeMap was missed initially to combine results from multiple Observables. The revised code snippet is as follows:
ReadAll(useCache?: boolean): Observable<ICustomerGroup[]> {
if (!this.customerGroupCache || !useCache) {
return this.http.get(this.urlGetAll)
.mergeMap((res: Response) => {
...
});
}
return Observable.of(this.customerGroupCache);
}
Merging all components together:
private buildCustomerGroupArray(allGroups: any, allCustomers: any): Array<ICustomerGroup> {
let result: Array<ICustomerGroup> = Array<ICustomerGroup>();
allGroups.forEach((group, index) => {
...
});
return result;
}