I have a problem working with websockets and displaying the changes in real-time.
I have an array of orders. This array is coming from a NodeJS backend server from calling on ngOnInit()
method my orderService.getOrders()
which fetches the orders from the backend through a REST call.
After this the orders are rendered into the template with the correct information.
I'm also using websockets to handle two type of events: placeOrder
(when a new order is submitted to the backed through POST) and updateOrder
(when an existing order is changed).
Here is a relevant part of that code:
webSocket.onmessage = function (event) {
const message = JSON.parse(event.data);
if (message === 'PlaceOrderEvent') {
self.handlePlaceOrderEvent(message);
} else if (message === 'UpdateOrderStatusEvent') {
self.handleUpdateOrderEvent(message);
}
};
This is working correctly and I can see the modified data inside those two methods if I console.log()
but the problem is that the changes are not reflected into the template only after I refresh the page.
I already tried using ChangeDetectorRef and calling detectChanges()
and the end of the handle()
methods but with no success.
How can this be achieved and display a new order in real-time into my template or display the changes to an existing one without refreshing the page?
EDIT: more relevant parts of the code
export class HomeComponent implements OnInit, OnDestroy {
orders: Order[];
constructor(private orderService: OrderService) { }
ngOnInit() {
this.getOrders();
this.openWebSocket();
}
self.orderService.getOrders().subscribe(
data => {
if (data.error) {
console.error(data.error);
} else {
if (Array.isArray(data)) {
self.orders = data.map(function (o) {
...
//parsing the data from the backend
}
openWebSocket() {
...
//onmessage
webSocket.onmessage = function (event) {
const message = JSON.parse(event.data);
if (message === 'PlaceOrderEvent') {
self.handlePlaceOrderEvent(message);
} else if (message === 'UpdateOrderStatusEvent') {
self.handleUpdateOrderEvent(message);
}
};
}
handlePlaceOrderEvent(order) {
const self = this;
self.orders.unshift({
...
//parsing the new order coming from websocket message
status: self.statuses[0],
placed: Date.now()
});
//<===== here I tried putting changeDetectorRef.detectChanges()
}