【发布时间】:2019-11-19 17:39:11
【问题描述】:
我有一个 Angular 应用程序,我为我的联系人列表创建了一个类,其中包括:
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
}
然后我有一个实例化这个类的服务,创建一个 BehaviorSubject 以与其他组件共享它并具有一些公共方法。
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);
}
}
然后,在一个组件中,我订阅了 BehaviorSubject 并将值影响到我的组件的一个属性。
ngOnInit() {
this.contactListSubscription = this.contactListService.getContactList().subscribe((newContactList) => {
this.contactList = newContactList;
});
}
所以它正在工作(即,当我通过服务执行操作时,所有内容都会随处更新)。但我不明白的是,订阅的内容(即this.contactList = newContactList)只在订阅时执行一次,而不是每次发生动作时执行。即使我通过 contactListService 方法更改内容。即使我取消订阅,比如订阅后 2 秒(例如使用 setTimeout),取消订阅后内容始终是最新的......
起初,我什至不明白为什么它在服务中起作用,而在每次修改对象的操作之后都没有执行contactList$.next(this.contactList.getContactList())。
所以看起来我传递了一些引用而不是类的内容?我想我不明白 BehaviorSubject 是如何工作的!
【问题讨论】:
标签: angular rxjs behaviorsubject