Kardon63
Kardon63

Reputation: 336

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

component 2: will get notified only if the second object in the array is changed

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

Upvotes: 0

Views: 1396

Answers (2)

kflo411
kflo411

Reputation: 124

So the subject will still be necessary, as you are saving state, but the filtering you can move to the shared service.

Create a method in the service that accepts an id parameter. Each component can now call this method with its ID, listening for only it's changes:

// 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))
            );
    }

Upvotes: 1

canbax
canbax

Reputation: 3856

You can simply put a public Subject or BehaviorSubject in a shared service.

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. You can subscribe to it and manually check if the first variable is changed or second is changed based on what you care.

Upvotes: 0

Related Questions