我正在实现一个数据存储服务,以在多个兄弟组件之间共享数据。每个组件都需要获得有关数据存储更改的通知。数据存储不会自行填充,需要从控制器设置数据。
data.store.ts
@Injectable()
export class DocumentIssueStore {
private _documentIssue: BehaviorSubject<DocumentIssueModel>;
constructor() {
this._documentIssue = new BehaviorSubject(null);
}
public setValue(newVal: DocumentIssueModel) {
this._documentIssue.next(cloneDeep(newVal));
}
public documentIssue(): Observable<DocumentIssueModel> {
return this._documentIssue.asObservable();
}
public current(): DocumentIssueModel {
return cloneDeep(this._documentIssue.getValue());
}
在两个组件的ngInit
方法中,我订阅了数据存储:
// Subscribe to changes in the store
this.storeSubscription = this.documentIssueStore.documentIssue().subscribe(
(data: DocumentIssueModel) => {
this.documentIssue = data;
}
);
问题:
更改任何组件中的this.documentIssue
会导致:
this.documentIssue
)this._documentIssue.getValue()
)目标:
- 在组件中具有单独的对象,可以通过调用setValue
方法将其更改然后发送到商店
答案 0 :(得分:1)
如果他们打算修改数据,每个订阅者都可以克隆数据:
// Subscribe to changes in the store
this.storeSubscription = this.documentIssueStore.documentIssue().subscribe(
(data: DocumentIssueModel) => {
this.documentIssue = cloneDeep(data);
}
);