简体   繁体   中英

RxJS Observables - multiple subscribers getting reference to same object

I've made an angular service to share state data across multiple components in my application. In order to share, it has a BehaviorSubject that can be subscribed to

export class DesignerService {
  private selectedFieldBehavior: BehaviorSubject<FormField> = new BehaviorSubject(this.selectedField);

  getSelectedField(): Observable<FormField> {
    return this.selectedFieldBehavior.asObservable();
  }
}

Multiple components subscribe to this via the getSelectedField() method. When I use next() to send a new object ( this.selectedFieldBehavior.next({ object }) ) , if any component subscribing to it modifies a property, all the subscribing components see that modification without notifying the service (like it's sending a reference instead of a copy), thus allowing the individual subscribers to modify each other's data

I've done a bit of work with angular/redux in the past, and I thought they promoted one-way dataflow and immutability. Reducers were the only way to modify the state, and then changes were propogated downwards to the subscribing components. What I currently have will allow child component to modify whatever they want. I'm not super experienced with building large angular apps that require state management. Am I mis-understanding how state management should work?

You can change your method a bit to return a clone

getSelectedField(): Observable<FormField> {
  return this.selectedFieldBehavior.asObservable().map(obj=>Object.assign({},obj));
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM