I'm working on piece of work where I need to use HTTP post
request, but it needs to be dynamic because the number of post requests to be made can vary.
I have an array of objects and I want to post each object to the httpClient
but so far it's only successfully posted the final object of the array.
EXAMPLE
I have an array like this
const planningChannels=[
{icon: "libraryBooks", name: "Blogs", type: "custom", color: "#dc4e41", purpose: "planning"},
{icon: "instagram", name: "instagram DM", type: "custom", color: "#50e3c2", purpose: "planning"},
{icon: "pinterest", name: "pinterest", type: "custom", color: "#535353", purpose: "planning"}
]
and I iterate through the array with a forEach loop:
planningChannels.forEach(channel => {
this.calendarService.createChannel(calendarId, channel)
.subscribe(
createdChannel => {},
error => this.notificationsService.apiError(error),
);
});
The calendarService.createChannel function look like this:
createChannel(calendarId: string,channel: Partial<IChannel>): Observable<IChannel> {
const requestUrl = `/calendar/${calendarId}/channel/`;
return this.http.post<IChannel>(requestUrl, channel).pipe(
tap(createdChannel => {
this.stateManager.dispatch(
{
id: calendarId,
channels: [createdChannel],
} as ICalendarUpdatedEntities,
CalendarEntitiesFetched
);
})
);
}
Each time I try and run this via the Chrome browser I can see all 3 network requests, but only that one is every visible on my front end. Can anyone help me on where I'm going wrong?
I don't think I can answer why not all 3 is visible on the front end. But I can suggest a more optimal way of doing your http requests, by using "merge" or "concat". With "merge", all your http request will fire at the same time. With "concat" the http requests will que up and each will go after the previous finished.
Instead of your forEach loop, you can do the following:
const pcObservables = planningChannels.map(channel => this.calendarService.createChannel(calendarId, channel));
concat(...pcObservables).subscribe(
createdChannel => {},
error => this.notificationsService.apiError(error),
);