Reputation: 37
I have array of values, will pass each array value to api call and I need to know how to save all response in single array in angular
this.result:[]=[];
this.formData=["S1", "S2"]
ngOnInit() {
for(let item of formData) {
this.httpClient.post(this.PartsAPIURL, item, { headers: headers })
.subscribe((data: any) => {
this.result.push(...data);
});
}
}
console.log(result);
Expected Result;
Response all should be stored in single array.
Upvotes: 1
Views: 359
Reputation: 14740
forkJoin
will make multiple requests and emit a single array of all responses:
public result: [] = [];
public formData = ['S1', 'S2'];
private requests = this.formData.map(
item => this.httpClient.post(this.PartsAPIURL, item, { headers })
);
private results$ = forkJoin(this.requests);
ngOnInit() {
this.results$.subscribe(
result => this.result = result
);
}
Upvotes: 1