In Angular 8
, I use the following approach in order to refresh Details
page after a new record added:
EventProxyService
export class EventProxyService {
private eventTracker = new BehaviorSubject<any>(undefined);
/* Allows subscription to the behavior subject as an observable */
getEvent(): BehaviorSubject<any> {
return this.eventTracker;
}
/* Allows updating the current value of the behavior subject */
setEvent(param: any): void {
this.eventTracker.next(param);
}
}
CreateComponent:
export class CreateComponent implements OnInit {
constructor(private eventProxyService: EventProxyService) { }
triggerAnEvent(param: any): void {
this.eventProxyService.setEvent(param);
}
}
DetailsComponent:
export class DetailsComponent implements OnInit {
subscription;
constructor(private eventProxyService: EventProxyService) { }
ngOnInit() {
this.subscription = this.eventProxyService.getEvent().subscribe((param: any) => {
this.theTargetMethod(param);
);
}
theTargetMethod(param) {
this.record = param; //update record via new one passed from service
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
The approach works as expected, but sometimes there are similar events e.g. Update that needs to refresh the Details
page. So, I am wondering if I should create a new BehaviorSubject
object (eventTracker
), getEvent
and setEvent
methods for each of different events e.g. Update
event? As far as I know, a single BehaviorSubject
can be used, but there may be a problem if two different events pass inconsistent data to the subscribers. What is the proper approach?