Share event/data between all instances of custom Angular16 components

60 views Asked by At

I need to share event/data between all instances of <my-component>. So, if user selects certain date in one instance then other instances of the same component should validate selected date and only allow dates after.

<div *ngFor="let parameter of parameterCollection">
  <my-component [p]="parameter" />
</div>

I tried shareable service of Subject observable, but it behaves like a single instance... I suspect my code isn't right.

Here's shareable service:

@Injectable()
export class FilteringService {


  /// observable string sources
  private announceSource = new Subject<string>();

  /// observable string streams
  missionAnnounced = this.announceSource.asObservable();

  /// service message commands
  announceMission(mission: string) {
    this.announceSource.next(mission);
  }

}

Here's my component (trimmed for brevity):

  constructor( private readonly _filteringSvc: FilteringService ) {
    _filteringSvc.missionAnnounced.subscribe( mission => {
      console.log('ANNOUNCED EVENT: ' + mission + ' for ' + this._parameterId);
    });
  }

  selectionChanged( newValue) {
    this._filteringSvc.announceMission( newValue);
  }
2

There are 2 answers

2
Rafael Zulianeli On

Change the Subject to BehaviorSubject, maybe that will help.

@Injectable()
export class FilteringService {


  /// observable string sources
  private announceSource = new BehaviorSubject<string>('');

  /// observable string streams
  missionAnnounced = this.announceSource.asObservable();

  /// service message commands
  announceMission(mission: string) {
    this.announceSource.next(mission);
  }

}
0
rBaun On

The code looks fine as it is, so I would assume the issue lies elsewhere.

Are you positive that the selectionChanged() method is being invoked as expected?