1

My application is being lazy loaded by a larger application when the user selects it from a menu. By this time the user is already authenticated and has proper roles, but due to the segmentation in the groups' apps, I still have to semi authenticate the user, by sending the username and special key to the server, for which I then get a token.

That token has to get loaded before I can do any other data requests. Right now I have a data service and part of it's constructor does this login. Unfortunately because http client is asynchronous, this means the first component from my app that is loaded fails to make it's data calls because the data service has just gotten created at this point...

Where should I be getting this token to avoid this?

dhockey
  • 312
  • 1
  • 11
  • I don't think performing a synchronous HTTP call is the real solution to your problem, not knowing whether that's actually possible. However, shouldn't your generic "dataService" or "apiService" be a global singleton that your lazy loaded module kind of reuses? If that service takes care of the authentication, your lazy loaded module only has to utilise the "dataService" in their e.g. ItemResourceService, not caring about how the actual rest communication happens (or what the absolute server path is) – Capricorn Aug 01 '18 at 15:11
  • This api service connects to our separate server and authenticates. Totally different different server to gather data from. I can't use their authentication or data service at all, other than to say that the user is authenticated by the time it gets to me. My thought right now is to move have component they get dumped on first that is a splash screen of sorts that redirects to the data requiring components when the service is ready. I'm rather new to angular though, so I'm just not sure how to approach this "the right way" – dhockey Aug 01 '18 at 15:16

1 Answers1

1

I believe what you are looking for is the HttpInterceptor.

First, you need to create a simple HTTP Interceptor as described in the official docs. Then, you can check if the token exists inside the interceptor before making any API calls, and run your calls sequentially using flatMap as described here.

After doing these, you will observe that http requests are made only after the authentication call has completed.

For the same requirement, prior to Angular's HTTPInterceptor release with 4.3, I had to create a CustomHttpClient, which had Angular's HttpClient injected in. To ensure that the http calls weren't made until an authentication token was retrieved, services in the app would only make http calls through this intermediate CustomHttpClient. Going through this step also allows to manipulate the Http calls, which is basically the "home-made" take on the Angular's new HttpInterceptor - https://stackoverflow.com/a/34465070/5116121

Uğur Dinç
  • 2,415
  • 1
  • 18
  • 25