首页 > 解决方案 > 在方法中使用 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 '。这是有道理的,因为它会为主题添加一个新属性,而不是替换现有的。

如何在尊重不变性的同时正确更新主题?

谢谢

标签: angularecmascript-6rxjs

解决方案


我想我了解您要完成的工作,但对于初学者来说,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);
}

不是最时髦的方法,但至少您不必手动检查每个值!


推荐阅读