Two httpClient request and one reference


I have auth.service.ts with HttpClient variable loaded from constructor with method for calling my api to get information about user and his privileges and if he has still valid token. I calling this method in constructor of my app.component.ts. Its working fine. But, in same page typescript files, I calling api to get initial data for that page. In that pages I have variable of HttpClient defined from constructor.

  1. problem: And because if that, sometimes I get response from second request soon then from first.
  2. problem: If I am not wrong, every HttpClient reference define in constructor for every page has same reference. Because If I call two request in same time, on of the response is every time empty.

Any idea how to resolve this? Thank you.

I can think of several strategies, but first I’d like to plead with you to get all direct mentions of HttpClient out of pages and into services. Pages should think solely in business object terms, and should neither know nor care from whence these business objects come - HttpClient, a runtime cache, on-device storage, &c. That way you can change the way you manage data without impacting how you present it at all. When those two activities get mashed together, the app becomes very hard to maintain.

So once you’ve done that, you can have a gatekeeper service that all services that interact with protected resources inject. The gatekeeper service can expose a “ready” Promise that is required to be waited on before attempting to fetch a protected resource. Another idea would be to implement this in an HttpInterceptor - this is how I generally do this, because it centralizes all the code. The interceptor is responsible for fetching and verifying tokens, as well as adding them in the needed headers to all requests. The trickiest part of this strategy is figuring out how to avoid the “Drawing Hands” situation of needing a token to get a token - it can be done by inspecting the URL or using a local custom header.