简体   繁体   中英

Display progress spinner while datas are loading in angular4 application

I have an angular 4 application and I get datas from a database with a springboot application. When I open my application, there is a get which returns data to display on the first page. So, I want to display a progress spinner while the datas are loading and when the datas are loaded, remove the spinner and display the datas.

So, I don't know how to do that. For now, this is my html code (the datas are displayed in visTimeline :

 <md-spinner id="isLoadingSpinner" style="margin:0 auto;"></md-spinner>
 <visTimeline (myTask)="returnTask($event)" [tasks]="tasks"></visTimeline>

And the ts code :

    ngOnInit() {
        this.tasks = this.datasService.getTasks();
        if(this.datasService.isLoading == false){
            document.getElementById("isLoadingSpinner").style.display = "none";
        }
    }

And this is the get in the datas.service :

    getAffectationsFromDataBase() {
  this.http.get('http://localhost:8081/affectation/findAll').map((response:Response) => {
        this.tasks.tasks = this.transformAffectations(response.json().affectations);
    }).subscribe(result =>  this.isLoading = false);
}

So, I try with if in the ngOnInit function and with a while but it doesn't work. Do you know how I can do that ?

The reason why it does not work is because the ngOnInit() method is synchronous and so it runs on the initialization of the page without waiting for any response.

You can use the [hidden] directive or *ngIf to solve this problem with the condition being the boolean from your "datasService" class. Adjust your HTML code in one of the following ways:

 <md-spinner [hidden]="!datasService.isLoading" id="isLoadingSpinner" style="margin:0 auto;"></md-spinner>

or

<md-spinner *ngIf="datasService.isLoading" id="isLoadingSpinner" style="margin:0 auto;"></md-spinner>

With one of these implementations you don't need to check the condition in ngOnInit();

I wrote a post here asking about how to do something in Ionic, based on the way you do things in Angular here . It covers your needs. Router Data Resolvers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM