0
votes

I have a form which loads user information from a BehaviorSubject. If I edit any input on this form and navigate away from the page WITHOUT hitting submit, the user information is updated in the subject regardless.

I do not have a grasp of why the Subject is being updated when I have not called next() on the BehaviorSubject.

===SUBJECT CLASS===

userDataReceiver$: Observable<UserModel>;
private userDataObserver = new BehaviorSubject(null);

constructor() {
    this.userDataReceiver$ = this.userDataObserver.asObservable();
}

 sendUserDataToSubscriber(data: UserModel) {
    this.userDataObserver.next(data);
}

===USER CLASS===

userDataReceiver: Subscription;

ngOnInit() {
    this.userDataReceiver = this.observerService.userDataReceiver$
    .subscribe(res => this.user = res);
}

ngOnDestroy() {
      this.userDataReceiver.unsubscribe();
}

this.user is being used in the form on the html page to load/save user data. If an input is edited in the html page without saving the form, navigating away from the page will still cause the user object to be updated. Navigating back to the html page will display the updated user input.

1

1 Answers

0
votes

Your form controls seem to be bound to the properties of the UserModel object emitted by the BehaviorSubject. So modifying the value in a control will modify the User. And since you have a BehaviorSubject, the next time you subscribe, you will get this exact same userModel object, with its modified properties.

If you don't want the form to modify the UserObject stored in the BehaviorSubject, then make a recursive copy of the object, and bind the properties of this copy in the form.