@ZahiC 的答案是正确的,但让我解释一下原因。
首先,对于 Rxjs,副作用越少越好。
不变性是你的朋友!否则,当你的应用程序不断增长时,试图猜测对象在哪里发生了变异将是一场噩梦。
第二,自从打字稿 2.1 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html您可以使用对象传播。这意味着要更新学生对象,而不是执行以下操作:
const newStudent = Object.assign({}, oldStudent, {name: 'new student name'});
你可以做:
const newStudent = {...oldStudent, name: 'new student name'};
在这两种情况下,您都不会改变原始学生,而是创建一个具有更新值的新学生。
最后一件事是如何将其与 Rxjs 结合起来。
The map
运算符的作用是:获取一个值,用它做你想做的事情,然后返回一个新的值,该值将在可观察链中使用。
所以,而不是:
student.map(student => student.name = 'Bob');
你应该这样做(正如@ZahiC 指出的):
student.map(student => ({...student, name: 'Bob'}));
为了避免隐藏变量名称,您可能还想调用您的可观察量:student$
student$.map(student => ({...student, name: 'Bob'}));
EDIT:
从 Rxjs 5.5 开始,您不应该使用 Observable.prototype 上修补的运算符,而应使用管道运算符:
student$.pipe(
map(student => ({...student, name: 'Bob'})),
tap(student => console.log(student)) // will display the new student
)