Search code examples
angulartypescriptrxjsbehaviorsubject

Can I emit object to stream with only one updated field?


I have one Behavior Subject that is a private field in my service

private data = new BehaviorSubject<Email>({
    body: '',
    email: ''
});

Can I create method for updating just one field of Email object and emitting it to stream? Something like this?

setBody(inputBody: string) {
    this.data.next({body: inputBody});
}

The problem here is I need to leave other field unchanged. Is it possible? Maybe it's possible to create one 'generic' method for updating any field by its name?


Solution

  • you must get current value of BehaviorSubject and then update your specific property

    setBody(inputBody: string) {
        const content = this.data.getValue()
        this.data.next({...content, body: inputBody});
    }