如何订阅 Angular 列表中的特定更改
How to subscribe to specific changes in a list in Angular
我有一个包含所有数据的列表,更新后我想通知特定订阅者:
示例:
arr = [{id:1, name: 'test1'}, {id:2, name: 'test2'}];
组件 1: 仅当数组中的第一个对象发生更改时才会收到通知
组件 2: 仅当数组中的第二个对象发生更改时才会收到通知
目前我正在使用 Subject
向所有订阅者发出所有更改,然后在组件上根据我的需要过滤结果
您可以简单地在共享服务中放置 public Subject
或 BehaviorSubject
。
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) { }
--编辑--
您可以创建一个 BehaviorSubject
数组对象。您可以订阅它并根据您的关心手动检查第一个变量是否更改或第二个变量是否更改。
因此主题仍然是必需的,因为您正在保存状态,但您可以将过滤移至共享服务。
在服务中创建一个接受 id 参数的方法。每个组件现在都可以用它的 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))
);
}
我有一个包含所有数据的列表,更新后我想通知特定订阅者:
示例:
arr = [{id:1, name: 'test1'}, {id:2, name: 'test2'}];
组件 1: 仅当数组中的第一个对象发生更改时才会收到通知
组件 2: 仅当数组中的第二个对象发生更改时才会收到通知
目前我正在使用 Subject
向所有订阅者发出所有更改,然后在组件上根据我的需要过滤结果
您可以简单地在共享服务中放置 public Subject
或 BehaviorSubject
。
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) { }
--编辑--
您可以创建一个 BehaviorSubject
数组对象。您可以订阅它并根据您的关心手动检查第一个变量是否更改或第二个变量是否更改。
因此主题仍然是必需的,因为您正在保存状态,但您可以将过滤移至共享服务。
在服务中创建一个接受 id 参数的方法。每个组件现在都可以用它的 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))
);
}