1

Take user global object as example. For a single page web app without refreshing the browser, the first entry could be populating the user object in the service.

But say, the URL is still being used as links to go to different route of the app. At what point, every component which using the user object in the route should be loading the user object from server? Since service is loading user asynchronously, how could these components in the current route can surely get the user before this user object is available?

I might be asking the wrong question because I want to solve this issue. So my thought is that if I can load the service object first before all other components, then it's solved.

I thought if I put service in app.component.ts, but it doesn't matter. Other components still being instantiated while user still undefined.

Hao
  • 6,291
  • 9
  • 39
  • 88

1 Answers1

6

You can use APP_INITIALIZER to ensure the value is loaded before Angular initializes the app, or you can use guards that delay routing until data becomes available.

See also

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I have tested this solution. It works. But still, this is marked in angular code as experimental? It seems to me there is really no alternative except this one to achieve what I want - make some service instantiated no matter what route is entered. https://github.com/angular/angular/blob/4.4.5/packages/core/src/application_tokens.ts#L64-L64 – Hao Oct 16 '17 at 08:36
  • That it is marked as experimental doesn't mean much. They might consider redesigning this feature eventually, but it's the same since 2.0.0-alpha. – Günter Zöchbauer Oct 16 '17 at 08:41