In
WebSockets: More than tech vanity, I talked about the implicit user value of asynchronous UIs. Today, here’s a neat little JavaScript trick I hadn’t been aware of that makes implementing them a bit easier: Object.assign(...).
Here’s the situation:
Your Angular frontend initially fetches a list of items from the backend. Thanks to Angular’s powerful data binding, many components reference properties of these objects. Later, the backend sends an updated version of one of these items via WebSocket. What now?
Sure, you can notify interested components via an RxJS subscription. But should every component compare the new object with the old one and manually update fields?
A more elegant approach: Notify the one component that for sure holds a reference to the object—in my case, the SaveListComponent. Then simply call:
Object.assign(oldObject, newObject);
This keeps the original object reference intact (so no list reordering or re-rendering quirks), while updating its properties in place. Thanks to Angular’s change detection, any component bound to that object sees the updated data automatically.