How to handle asynchronous call to API?

300 views Asked by At

I have array of JSON Object and have to add the result of API hit with each JSON Object, to certain element of each JSON object, and the final result should be display in HTML file? But HTML pages already renders before the data retrieved from the API?

The issue is something like this:

<tr *ngFor="let order of Orders">
    <td><img src="images/honey.jpg" style="width:50px;"/>
        <span style="margin-left:10px;">{{order.productName}} <strong>[ package:</strong> {{order.packageName}}<strong>]</strong></span></td>
    <td><input type="number" class="form-control" step="1" style="width:80px;" [value]="order.quantity" /></td>
    <td><span>NPR Rs.{{order.Rate|number}}</span></td>
    <td><strong>{{order.totalPrice}}</strong></td>
    <td>
        <a href="#" style="color:#F00"><i class="fa fa-trash" (click)="removeItem(order)"></i> Remove</a>
    </td>
</tr>

Only totalPrice is calcuating from the API side, and all others contents are already with the Orders variable.

At ts file:

calculatePrice(){
     let i;
     for(i =0;i<this.Orders.length; i++){
         this.dataService.post("order/prices",this.Orders[i])
             .subscribe(res=>{
                 this.Orders[i]['totalPrice'] = res.totalPrice;
             })
     }
}
1

There are 1 answers

0
Günter Zöchbauer On BEST ANSWER

You can use *ngIf="data" on an element in your component to prevent rendering before data got a value or
you can use a guard to prevent routing to a component before the data is available https://angular.io/docs/ts/latest/guide/router.html#!#guards

You can also block the initialization of the whole Angular2 application until the data from the server becomes available How to pass parameters rendered from backend to angular2 bootstrap method