更改可观察值 [英] Change value in an observable

查看:92
本文介绍了更改可观察值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个可观察的学生:Observable< Student> 其中学生的参数 name:string 设置为 Jim ,如何更改 name的值学生可观察到鲍勃

If I have an observable student: Observable<Student> where Student has the parameter name: string is set to Jim, How can I change the value of name in the students observable to be Bob?

编辑:

student.map(student => student.name ='Bob')应该有效。因为如果是,那么我的程序还有其他问题。

Is student.map(student => student.name = 'Bob') supposed to work. Because if yes then there is something else wrong with my program.

推荐答案

@ ZahiC的答案是对的,但让我解释一下一点点原因。

@ZahiC's answer is the right one, but let me explain a little bit why.

首先,使用Rxjs,你的副作用越少越好。
Immutability是你的朋友!否则,当你的应用程序增长时,试图猜测某个对象的变异位置将是一场噩梦。

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.

其次,因为 Typescript 2.1 你可以使用对象传播。这意味着更新学生对象,而不是:

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'});

你可以这样做:

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.

最后一件事,就是如何将它与Rxjs结合起来。

地图运算符就在这里:取一个值,用它做你想做的事情并返回一个新的,它将用于可观察链。

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.

所以,而不是:

student.map(student => student.name = 'Bob');

你应该这样做(如@ZahiC指出的那样):

You should do (as @ZahiC pointed out):

student.map(student => ({...student, name: 'Bob'}));

为了避免隐藏变量名称,你可能还想调用你的observable:学生$

And in order to avoid shadowing variable name, you might also want to call your observable: student$

student$.map(student => ({...student, name: 'Bob'}));

编辑:

由于Rxjs 5.5你应该不要使用在Observable.prototype上修补的运算符而是使用管道运算符:


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 
)

这篇关于更改可观察值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆