I have an Angular app and I created a class for my contact list which consists of:
export interface Contact {
id: number;
name: string;
address: string;
}
export class ContactList {
private contactList: Contact[];
private contactNumber: number;
public getContactList(): Contact[] {
return this.contactList;
}
// Methods to add, modify and remove a contact
}
Then I have a service that instantiates this class, creates a BehaviorSubject to share it with other components and has some public methods.
export class ContactListService {
public contactList: ContactList;
private contactList$: BehaviorSubject<Contact[]>;
constructor() {
this.contactList = new ContactList(FAKE_CONTACTS);
this.contactList$ = new BehaviorSubject<Contact[]>(this.contactList.getContactList());
}
public getContactList(): BehaviorSubject<Contact[]> {
return this.contactList$;
}
public deleteContact(contactId: number): void {
this.contactList.deleteContact(contactId);
}
public addContact(newName: string, newAddress: string): void {
this.contactList.addContact(newName, newAddress);
}
public modifyContact(contactId: number, newName?: string, newAddress?: string): void {
this.contactList.modifyContact(contactId, newName, newAddress);
}
}
Then, in a component, I subscribe to the BehaviorSubject and affect the value to a property of my component.
ngOnInit() {
this.contactListSubscription = this.contactListService.getContactList().subscribe((newContactList) => {
this.contactList = newContactList;
});
}
So it's working (ie. everything is update everywhere when I perform an action via the service). But what I don't understand is that the content of the subscription (ie. this.contactList = newContactList) is only performed one time at the subscription and not every time an action occurs. Even if I change the content via a contactListService method. And even if I unsubscribe, like 2s after subscribing (with a setTimeout for example), the content is always up to date after the unsubscribing...
At first, I even didn't understood why it works in the services without doing a contactList$.next(this.contactList.getContactList()) after every actions that modify the object.
So it seems like I passed some references instead of the content of the class? I think I don't understand how BehaviorSubject works!