I have a few Angular components, and I use BehaviorSubject to pass event among them.
Service:
@Injectable()
export class SiteManagementEventService {
private messageSource = new BehaviorSubject<SiteManagementEvent>(defaultEvent);
data = this.messageSource.asObservable();
constructor() {}
// publish the event using the service
public publish(event: SiteManagementEvent) {
if (event !== null) {
this.messageSource.next(event);
}
}
}
Publishing events:
constructor (
.......
private eventService: SiteManagementService,
) {}
........
this.eventService.publish(event);
Subscribe the events:
constructor (
.......
private eventService: SiteManagementService,
) {}
onInit() {
......
this.eventService.data.subscribe(event => {console.log("event received"});
}
By having the above, the issue is that only one receiving component (I have multiple receiving components) receives one event, and do not receive any following events.
Anything I did wrong? Any online samples for this?
Thanks!
You are using BehaviorSubject correctly. It will replay the last emitted value to new subscriptions.
Ensure that your service is a singleton by using @Injectable({provideIn: "root"})
.