Weshahi
Weshahi

Reputation: 23

Angular 2, how to stop loading app until response of http request

I faced a problem in Angular 2 I need to get data from server by Http Request before loading any other components ,in other words stop the app from loading/ rendering any component till the response of the Request coming .

in another words how to stop loading the app till get data from database

Upvotes: 1

Views: 4714

Answers (3)

mohit uprim
mohit uprim

Reputation: 5334

Use the resolver to get the data first and initialise the component after receiving the data

For Example: UserComponent would be initialised after getting the users data.

{ path: 'user', component: UserComponent, resolve: { users: UserDataResolver }

For more detail, check my following answer: Fetching data from a ReST Micro service in angular 2

Demo:https://plnkr.co/edit/uSgmIw?p=templates

However, fetching data before loading the component could break the UX. Sometimes you need it but most of time a local loader strategy is better (display a loader while data is fetching)

Also refer to following related resource:
https://angular.io/guide/router#resolve-pre-fetching-component-data

Upvotes: 4

redfox05
redfox05

Reputation: 3682

Sounds like what you might be looking for a way to intercept the initialization of your Angular app before the http request is complete.

If so, I would suggest looking at APP_INITIALIZER

This can be used to hook into the loading process in angular, and you can trigger a service that returns a Promise. The rest of the app won't load until that promise is resolved.

The key thing to remember it that it uses Promises, NOT Observeables. The API docs are not clear on that.

More info can be found here:

Upvotes: 0

omkar94
omkar94

Reputation: 11

From Angular 4.3.0 HttpClientModule supports interceptors. You can use it to show the loading indicator until your data is fetched. This is will give a better user experience. https://angular.io/guide/http

Upvotes: 1

Related Questions