Right now I'm using forkJoin
on an array of observables, which works well. However, I need to associate each observable with another property so that I can track the property after subscribing to the forkJoin
.
So right now, my array of values:
randoArray = ["3", "4", "8", "9"];
Creating the array of observables and returning the forkJoin:
this.randoArray.forEach(key => {
this.observableBatch.push(this.getDocument(key));
});
return forkJoin(this.observableBatch);
But what I need to do is instead have an array of objects, so for each object there would be one property for the name and one property for the item I need to create an observable for... this way once I subscribe I get the result of the observable along with a name for it.
newArray = [
{ name: "testName", value: "3" },
{ name: "testName2", value: "4" },
{ name: "testName3", value: "8" },
{ name: "testName4", value: "9" }
];
this.newArray.forEach(item => {
this.observableBatch.push({ observable: this.getDocument(item.key), name: item.name });
});
But I can't run a forkJoin on the array of objects because it's now an array of objects with properties that aren't just observables, ie I can't do this:
return forkJoin(this.observableBatch);
I'm not sure how to do this. I need to forkJoin
just the observables in an array of objects and somehow keep track of each name property.
StackBlitz: https://stackblitz.com/edit/angular-ivy-nkunke?file=src/app/app.component.ts
Full code:
export class AppComponent {
constructor(private http: HttpClient) {}
randoArray = ["3", "4", "8", "9"];
// I want to keep the name property and associate them w/ each observable
newArray = [
{ name: "testName", value: "3" },
{ name: "testName2", value: "4" },
{ name: "testName3", value: "8" },
{ name: "testName4", value: "9" }
];
observableBatch = [];
display = "";
test2() {
this.getObservables().subscribe(data => {
console.log(data);
this.display = JSON.stringify(data);
// reset
this.observableBatch = [];
});
}
getObservables() {
this.randoArray.forEach(key => {
this.observableBatch.push(this.getDocument(key));
});
console.log(this.observableBatch);
return forkJoin(this.observableBatch);
}
getDocument(id: string) {
return this.http.get(`https://jsonplaceholder.typicode.com/todos/${id}`);
}
}
Any help would be much appreciated.