假设我有一个行为主体,它的值由一个具有两个属性的对象组成.有没有办法只订阅基础值的一个属性的更改?

export interface MyObject {
  property1: string,
  property2: string
};
const subject = new BehaviorSubject<MyObject>({
  property1: 'test',
  property2: 'test'
});
subject.next({
  property1: 'test',
  property2: 'test2'
});
subject.subscribe(value => {
  // how to only fire for changes on property2?
});

推荐答案

您可以使用distinctUntilChanged运算符,并传入一个函数,该函数描述了什么算作相等.如果两个连续的值相等,则会过滤掉第二个值:

subject.pipe(
  distinctUntilChanged((prev, curr) => prev.property2 === curr.property2)
).subscribe(value => {
  // do stuff
})

等效地,您可以使用distinctUntilKeyChanged:

subject.pipe(
  distinctUntilKeyChanged('property2')
).subscribe(value => {
  // do stuff
})

以上示例仍将输出整个对象.如果您只想输出属性2,那么您可以改为映射到该属性,并再次使用DiffertUntilChanged,尽管您不需要自定义相等函数

subject.pipe(
  map(value => value.property2),
  distinctUntilChanged(),
).subscribe(property2 => {
  // do stuff
})

Angular相关问答推荐

Angular ngModel双向数据绑定不适用于表单中的Select元素

Angular :仅当 Select 第一个日期时才显示第二个日期字段

垫-菜单未以17.2.3角显示

Angular 如何观察DOM元素属性的变化?

使用`UrlHandlingStrategy`更改位置

在Angular 17的本地服务应用程序时禁用SSR

P-DropDown不会使用react 式表单手动设置Value

如何将参数传递给Angular 服务

Angular 懒惰地加载一个服务

具有两个订阅方法的 Angular 16 takeUntilDestroyed 运算符

使用 RXJS 进行空闲/不活动跟踪

如何在 Angular14 中创建带有验证的自定义输入组件?

组件的导入不能以Angular 工作

错误:在工作区外运行 Angular CLI 时,此命令不可用

如何在 Angular 2 中使用 protractor ?

在 Ionic 2 中使用图像资源的正确方法

如何在Angular2中基于特定的构建环境注入不同的服务?

Angularmaterial步进器:禁用标题导航

AOT - Angular 6 - 指令 SomeComponent,预期 0 个参数,但go 有 1 个参数

找不到模块angular2/core