Search code examples
angulareventemitter

Delay in displaying the content on UI


I have two components in my angular project. One is singleOrder form component and the other component is to display all the orders as list. If I fill the singleOrder form and click submit it should instantiate the orderList component which will internally fetch the data from DB through an API call. For that functionality I used EventEmitter.

My singleOrder component looks like below.

onSubmit(form: NgForm) { // in submit button I am calling this 
console.log(form);
this.insertRecord(form); // inserts an order in DB through an API
// this.service.wait(7000); // wait function
this.service.OrderEvent.emit(); // here it initialize the second component

}

My OrderList component looks like this.

ngOnInit() {
console.log("ngoninit");
this.service.OrderEvent.subscribe(() => { // fetching data from DB
  console.log("order event");
  this.service.refreshList()
    .subscribe(
      data => {
        this.Orderlist = data; // displaying on UI
        this.orderCollectionSize = this.Orderlist.length;
      }
    );
    console.log(this.Orderlist);
});}

I am displaying orderlist on my UI. As I am using events until I click submit from first component my Orderlist field will be empty and nothing will be displayed on UI.

I have below code which will split the orderlist across pages as below

get Orders(): SingleOrder[] {
// console.log(this.Orderlist);
if (!this.Orderlist) { return; }
return this.Orderlist
  .slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize);

}

I am using this Orders variable on UI as below

<tr *ngFor="let order of Orders ">
    <!-- <mat-checkbox></mat-checkbox> -->
    <td (click)="openDialog(order)">{{order.orderId}}</td>
    <td (click)="openDialog(order)">{{order.orderStatus}}</td>
    <td (click)="openDialog(order)">{{order.paymentMethod}}</td>
    <td (click)="openDialog(order)">{{order.orderTotal}}</td>
    <td (click)="openDialog(order)">{{order.orderSubtotal}}</td>
    <td (click)="openDialog(order)">{{order.orderTax}}</td>
    <td (click)="populateForm(order)">{{order.orderShippingCharges}}</td>
  </tr>

Say suppose I have 10 orders already in my DB and inserting one more from the first component by filling up the form, I expect 11 orders in total on UI. But I am getting only 10. Without refreshing the whole page is there a solution for this as refreshing is gonna take much time.

Tried giving some delay in first component as shown as comments above but didn't help.


Solution

  • Here the problem is to fetch record before save so you need to subscribe to insert record method

    this.insertRecord(form).subscribe(result=> { 
    this.service.OrderEvent.emit(); 
    }, err=> {});
    

    So once you will get done with insert then raise event