In Angular, if I have one part of the screen populated by an HTTP GET request and another part of the screen populated by a completely different GET request, but the second request should only get called after the first completely finishes, what is the preferred way (i.e. best practice) to accomplish this?
CodePudding user response:
I would suggest creating a dependency on the first request while using switchMap
to mutate the inner observable of the second request.
public firstResponse$ = this.http.get('api/endpoint').pipe(share());
public secondResponse$ = this.firstResponse$.pipe(switchMap(() => this.http.get('api/other-endpoint')));
This creates a stream that will ensure that the second request isn't triggered until the first request returns with a response.
Note the share()
operator which will avoid making multiple requests when subscribed to multiple times.