I've just started exploring the new Signals API in Angular. I was informed that data should be treated as immutable when using signals.
Now, I am unsure if it is possible to implement something similar with JS Maps:
// code within my service.
// Utilizing a Map to store messages in an object and retrieve them by queue name.
messages = signal(new Map<string, Object>());
queryForMessagesInQueue(queue) {
this.httpClient.get('...').subscribe((newMessagesArray) => {
const messages = this.messages().get(queue) || {};
// Checking if newMessages already exist in the message object
let addedMessages = 0;
newMessagesArray.forEach((newMsg) => {
const messageExists = !!messages[newMsg.id]
if (messageExists == false) {
messages[newMsg.id] = newMsg;
addedMessages++;
}
});
if (addedMessages !== 0) {
this.messages.update((msgMap) => msgMap.set(queue, messages));
}
});
}
In my components, I have implemented the following:
export class MyComponent {
private service = inject(MyService)
messages = service.messages; // references the service signal.
}
Am I correctly utilizing it?
Can signals integrate seamlessly with data structures like JS Maps? Will change detection function properly?
Appreciate your assistance in advance.