简体   繁体   English

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

[英]How to subscribe to specific changes in a list in Angular

I have a list containing all the data, when updated I want to notify specific subscribers:我有一个包含所有数据的列表,更新时我想通知特定订阅者:

example:例子:

arr = [{id:1, name: 'test1'}, {id:2, name: 'test2'}];

component 1: will get notified only if the first object in the array is changed组件 1:仅当数组中的第一个 object 更改时才会收到通知

component 2: will get notified only if the second object in the array is changed组件 2:仅当数组中的第二个 object 更改时才会收到通知

Currently I am using Subject to emit all changes to all subscribers and then on the components I am filtering the result depending on what I need目前我正在使用Subject向所有订阅者发出所有更改,然后在组件上我根据我的需要过滤结果

So the subject will still be necessary, as you are saving state, but the filtering you can move to the shared service.所以主题仍然是必要的,因为您正在保存 state,但您可以将过滤移至共享服务。

Create a method in the service that accepts an id parameter.在接受 id 参数的服务中创建一个方法。 Each component can now call this method with its ID, listening for only it's changes:现在每个组件都可以使用它的 ID 调用这个方法,只监听它的变化:

// in your service

arrSubject = new Subject<{id, name}[]>();
...
dataHasChanged(id: string): Observable<{}> {
        return this.arrSubject.asObservable().pipe(
            map(arr => arr.filter(x => x.id === id)),
            distinctUntilKeyChanged('name') 
            // or, check if anything changed... basic string or custom compare function
            // distinctUntilChanged((a, b) => JSON.stringify(a) === (JSON.stringify(b))
            );
    }

You can simply put a public Subject or BehaviorSubject in a shared service.您可以简单地将公共SubjectBehaviorSubject主题放在共享服务中。

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) { }

--edit-- You can make a BehaviorSubject that is objects of array. --edit-- 您可以创建一个BehaviorSubject ,它是数组的对象。 You can subscribe to it and manually check if the first variable is changed or second is changed based on what you care.您可以订阅它并根据您关心的内容手动检查第一个变量是否已更改或第二个变量是否已更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM