Change value in an observable
@ZahiC's answer is the right one, but let me explain a little bit why.
First, with Rxjs, the less side effects you have, the better. Immutability is your friend! Otherwise, when your app will grow, it's going to be a nightmare trying to guess where an object has been mutated.
Second, since Typescript 2.1 you can use the object spread. Which means that to update a student object, instead of doing:
const newStudent = Object.assign({}, oldStudent, {name: 'new student name'});
You can do:
const newStudent = {...oldStudent, name: 'new student name'};
In both case, you're not mutating the original student, but rather creating a new one with an updated value.
Last thing, is how to combine that with Rxjs.
The map
operator is here for that: Take a value, do what you want with it and return a new one which is going to be used down the observable chain.
So, instead of:
student.map(student => student.name = 'Bob');
You should do (as @ZahiC pointed out):
student.map(student => ({...student, name: 'Bob'}));
And in order to avoid shadowing variable name, you might also want to call your observable: student$
student$.map(student => ({...student, name: 'Bob'}));
EDIT:
Since Rxjs 5.5 you should not use operators patched on Observable.prototype and use the pipe operator instead:
student$.pipe(
map(student => ({...student, name: 'Bob'})),
tap(student => console.log(student)) // will display the new student
)
Zachscs
I graduated from California State University, Northridge with a degree in Computer Science. I work full time as a full stack developer in Los Angeles. I like using vim or vscode for my projects. I play tennis and enjoy craft beer, classic rock and watching sports.
Updated on June 08, 2022Comments
-
Zachscs almost 2 years
If I have an observable
student: Observable<Student>
whereStudent
has the parametername: string
is set toJim
, How can I change the value ofname
in thestudents
observable to beBob
?Edit:
Is
student.map(student => student.name = 'Bob')
supposed to work. Because if yes then there is something else wrong with my program. -
krillgar over 5 yearsOne note, the
map
function is declared in'rxjs/operators'
. -
Mickers almost 5 yearsIf anyone is wondering why the tap in the above example doesn't fire it's because you have to subscribe to it.
-
maxime1992 almost 5 yearsOh yes I could have been more precise and explain that you have to subscribe to it but it's also one of the first thing you learn with observables. @Mickers if you want to know more about that google cold vs host observables :)