1

In the following code, how can I make the orderItems auto refresh after I call addOrderItem()? Currently I have to call this.service.getOrderItems() again to manually refresh it.

export class OrderComponent implements OnInit {
    orderItems: OrderItem[];
    ...
    ngOnInit() {
        ...
        this.orderItems = this.service.getOrderItems();
    }
    addOrderItem(): void {
        this.service.addOrderItem();
    }
}
user2226125
  • 29
  • 1
  • 4
  • adding an item to a data bound array should already auto refresh without you needing to do anything – Michael Kang Oct 27 '18 at 02:54
  • @pixelbits The order items array is returned by the service which I think is a deep copy of the original array. When I call the service to add things to the original array, this deep copy does not refresh but the original array does. – user2226125 Oct 27 '18 at 04:01
  • Ah,I understand they are different arrays. – Michael Kang Oct 27 '18 at 04:03

1 Answers1

1

You encapsulated your addOrderItem() service method so you can call getOrderItems in this encapsulation so it will be refreshed each time you add an OrderItem:

addOrderItem(): void {
  this.service.addOrderItem();
  this.orderItems = this.service.getOrderItems();
}

You can also subscribe to an event from your service to call a function each time addOrderItem() is called.

Maarti
  • 3,600
  • 4
  • 17
  • 34