I have a tree like structure in the frontend, that might look like the tree from the image above. Due to the way, the Backend is designed, I have to persist each node individually. But to persist a node it has to know it's parents id. I decided to persist the nodes in a top down, depth first order, which is [a,b,d,e,c]
.
I use HttpClient.post() which returns an Observable. To persist b
I have to wait for HttpClient.post(a)
to return the id of a
, which is needed to persist b
.
The only way I could imagine. Is the following:
of(1).pipe(
mergeMap(() => httpClient.post(a)),
tap(idOfA => b.parentId = idOfA),
tap(idOfA => c.parentId = idOfA),
mergeMap(() => httpClient.post(b)),
tap(idOfB => d.parentId = idOfB),
tap(idOfB => e.parentId = idOfB),
mergeMap(() => httpClient.post(d)),
mergeMap(() => httpClient.post(e)),
mergeMap(() => httpClient.post(c))
).subscribe();
You could ignore the tap()
stuff, because it happens automatically in the background. It's just there to make clear, why the request depend on their parents requests to return. Simplified it looks like this:
of(1).pipe(
mergeMap(() => httpClient.post(a)),
mergeMap(() => httpClient.post(b)),
mergeMap(() => httpClient.post(d)),
mergeMap(() => httpClient.post(e)),
mergeMap(() => httpClient.post(c))
).subscribe();
make a request, wait for it to return, make another request and so on. The stuff I implemented above works for any preordered list of 5 nodes. The thing is, I have to do that dynamically, for a list of variable size.
Could you please give me a hint on how to do that in any kind of loop or loop like construct?
You can use concatMap()
and parentId
variable stores the latest parent Id -
parentId: any;
of(a, b, c, d) // or you can also pass an array using from([a, b,c ,d])
.pipe(concatMap(val => httpClient.post('url', { parentId: this.parentId })))
.subscribe(res => {
this.parentId = res.id;
console.log(res);
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments