angular - 在方法中使用 next() 更新 RXJS 主题,如何处理参数?
问题描述
假设我有一个服务,在 Angular 中有一个主题。我实现了一个updateSubject
将.next()
在这个主题上使用的方法。这个想法是在其他组件中使用此服务的方法。
interface MyInterface {
name: string;
age: number;
}
export class myService {
private mySubject: BehaviorSubject<MyInterface >;
updateSubject(newData) {
this.mySubject.next({...this.mySubject.value, newData);
}
}
export class myComponent {
constructor(private myService: myService){}
update() {
this.myService.updateSubject({age:30});
}
}
问题是,我不能像 tslint 告诉我的那样继续下去Argument of type {newData: any, name: string, age: number} is not assignable to parameter of type 'MyInterface '
。这是有道理的,因为它会为主题添加一个新属性,而不是替换现有的。
如何在尊重不变性的同时正确更新主题?
谢谢
解决方案
我想我了解您要完成的工作,但对于初学者来说,next()
接受一个参数并为主题分配该值。进行部分添加(例如仅添加年龄)的一种方法是获取当前值,将其与新值合并,然后将该值传递给。
const holderData: MyInterface = {
name: 'fred',
age: 40
}
merge(defaultData, newData): MyInterface {
for (const key in newData) {
if (newData.hasOwnProperty(key)) { defaultData[key] = newData[key]; }
}
return defaultData;
}
updateSubject(newData: MyInterface){
const mergedData = this.merge(this.holderData, newData);
this.mySubject.next(mergedData);
}
不是最时髦的方法,但至少您不必手动检查每个值!
推荐阅读
- php - 如何从 sql 数据库中的单个单元格下载多个文件?我正在使用 laravel 5.5
- c++ - 机器学习/openVino代码中动物园文件的目的是什么
- reactjs - 使用 Socket.io 重置反应状态
- .net - 如何让我的 python 代码在 15 毫秒内执行
- javascript - 如何在innerHTML 中搜索复选框?
- python - 如何在云端运行 Selenium Python 脚本?
- reactjs - Axios - 提取 http cookie 并将其设置为授权标头
- javascript - 面对类装饰器的 Linting 问题
- f# - 将 List.AddRange 与 F# 列表一起使用的语法是什么?
- c# - 当我不给它任何输入时,我将如何增加汽车的摩擦力使其不会滑行?