Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何订阅列表中的特定更改_Angular_Rxjs_Observable - Fatal编程技术网

Angular 如何订阅列表中的特定更改

Angular 如何订阅列表中的特定更改,angular,rxjs,observable,Angular,Rxjs,Observable,我有一个包含所有数据的列表,更新后我想通知特定订阅者: 例如: arr = [{id:1, name: 'test1'}, {id:2, name: 'test2'}]; 组件1:仅当阵列中的第一个对象发生更改时才会收到通知 组件2:仅当阵列中的第二个对象发生更改时才会收到通知 目前我正在使用Subject将所有更改发送给所有订阅者,然后在组件上根据需要过滤结果您只需将公共主题或行为主题放入共享服务中即可 import { BehaviorSubject } from 'rxjs'; expo

我有一个包含所有数据的列表,更新后我想通知特定订阅者:

例如:

arr = [{id:1, name: 'test1'}, {id:2, name: 'test2'}];
组件1:仅当阵列中的第一个对象发生更改时才会收到通知

组件2:仅当阵列中的第二个对象发生更改时才会收到通知


目前我正在使用
Subject
将所有更改发送给所有订阅者,然后在组件上根据需要过滤结果

您只需将公共
主题
行为主题
放入共享服务中即可

import { BehaviorSubject } from 'rxjs';
export class SharedService {
  firstPage = new BehaviorSubject<any>(null);
  secondPage = new BehaviorSubject<any>(null);
}


# import the service inside the constructor of the components as usual

constructor(private _s: SharedService) { }
从'rxjs'导入{BehaviorSubject};
导出类共享服务{
firstPage=新行为主体(null);
第二页=新行为主体(空);
}
#照常在组件的构造函数中导入服务
构造函数(私有_s:SharedService){}
--编辑--
您可以创建一个
行为主体
,它是数组的对象。您可以订阅它,并根据您所关心的内容手动检查第一个变量是否更改或第二个变量是否更改。

因此,在保存状态时,主题仍然是必需的,但您可以移动到共享服务

import { BehaviorSubject } from 'rxjs';
export class SharedService {
  firstPage = new BehaviorSubject<any>(null);
  secondPage = new BehaviorSubject<any>(null);
}


# import the service inside the constructor of the components as usual

constructor(private _s: SharedService) { }
在服务中创建一个接受id参数的方法。现在,每个组件都可以使用其ID调用此方法,只侦听其更改:

//在您的服务中
arrSubject=新主题();
...
dataHasChanged(id:string):可观察{
返回此.arrSubject.asObservable()管道(
映射(arr=>arr.filter(x=>x.id==id)),
distinctUntilKeyChanged('name'))
//或者,检查是否有任何更改…基本字符串或自定义比较函数
//distinctUntilChanged((a,b)=>JSON.stringify(a)==(JSON.stringify(b))
);
}

distinctUntilChanged
带有自定义比较功能。您是否自己更改对象?您知道何时更改它们吗?@canbax我通过调用后端,每1分钟更新一次列表services@martin@马丁:我会检查你的建议,如果你的病情只是第一个a,我会把结果重播给你数组中的第二个对象,你可以创建两个单独的观察对象并为它们提供数据。谢谢你的回答,但这不是我想要的,正如我已经在使用
主题
的问题中提到的,但我不想推送所有的更改,然后签入组件,我只想得到对组件很重要的特定更改t-特异性成分