Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 load data before rendering the app

In my main component's ngOnInit I do get some global settings :

ngOnInit() {
   this._service1.initGlobalData()
   this._service2.initGlobalData2()
}

these 2 calls initialize _service1 and _service2 which are then used in several different places in my app. I would like to be sure these 2 calls are done before starting rendering my application.

Is there any specific way to do it in Angular 2 ?

The only solution that comes up to my mind would be to set a spinner up based on the promises returned by these two init calls.

like image 751
Scipion Avatar asked Jun 21 '16 14:06

Scipion


3 Answers

The answer is not very popular but I think the easiest way it to just wrap your template with *ngIf="data" then the template will only be rendered after data has a value assigned.

The router (depending on what version you're using) might have lifecycle callback that allows to delay the component to be added until a promise is resolved.

like image 160
Günter Zöchbauer Avatar answered Sep 29 '22 02:09

Günter Zöchbauer


You can use https://angular.io/docs/ts/latest/api/core/index/APP_INITIALIZER-let.html

An example (take a look at the bottom of the page): https://github.com/angular/angular/blob/master/modules/%40angular/router/src/common_router_providers.ts

like image 28
Nguyễn Việt Trung Avatar answered Sep 29 '22 02:09

Nguyễn Việt Trung


Normally my team and I use ngIf to render the content when it's ready. Something like:

<div *ngIf="_service1">
   // content for _service1
</div>
<div *ngIf="_service2">
   // content for _service2
</div>

like image 39
Reginaldo Camargo Ribeiro Avatar answered Sep 29 '22 01:09

Reginaldo Camargo Ribeiro