I need to update data in angular from mongodb

Viewed 52

I have an angular project with a springBoot api and a mongodb database My problem is that I need one of the components to update at the same time as information is injected into the database It is an order app where orders are made from a component and saved in the database

  addOrder(): void{
this.apiService.createOrder(
  this.username,
  this.pedido.tableNumber,
  this.pedido.platos,
  this.pedido.totalPrice
).subscribe( orderResponse => {
  if (orderResponse) {
    this.dialog.open(DialogOrderComponent);
  } else {
    this.dialog.open(DialogOrderFalseComponent);
  }
})

}

but I need that when the database changes the new orders are shown in the component that is in charge of displaying them

1 Answers

You can create simple Service for Entity holding, something like that:


@Injectable()
export class OrderService{

    private orders: OrderDto[] = [];

    constructor(private apiService: ApiService){}

    loadOrders(){
        this.apiService.loadAllOrders().subscribe(orders => {
            if(orders){
                this.orders = orders;
            }else{
                //Handle error   
            }
        });
    }

    getOrders(): OrderDto[] {
        return this.orders;
    }

}

And just call loadOrders every time you are creating a new order:

addOrder(): void{
    this.apiService.createOrder(
        this.username,
        this.pedido.tableNumber,
        this.pedido.platos,
        this.pedido.totalPrice
    ).subscribe( orderResponse => {
        if (orderResponse) {
            this.orderService.loadOrders();
            this.dialog.open(DialogOrderComponent);
        } else {
            this.dialog.open(DialogOrderFalseComponent);
        }
})

After that use ordersService.getOrders() in your component

Related