Shared service is a common way of communication between unrelated components. Your components must use a single instance of the service , so make sure it is listed at the root level.
Example using BehaviorSubject as a data delegate :
General service:
@Injectable() export class SharedService { isVisibleSource: BehaviorSubject<boolean> = new BehaviorSubject(false); constructor() { } }
Component 1:
export class Component1 { isVisible: boolean = false; constructor(private sharedService: SharedService) { } onClick(): void { this.isVisible = !this.isVisible; this.sharedService.isVisibleSource.next(this.isVisible); } }
Component 2:
export class Component2 { constructor(private sharedService: SharedService) { } ngOnInit() { this.sharedService.isVisibleSource.subscribe((isVisible: boolean) => { console.log('isVisible: ', isVisible);
It is worth noting that BehaviorSubject upon subscription, returns the last value that it has, so the component from the above example will be updated with the most recent value immediately after creating the instance.
BehaviorSubject also allows you to get the most recent value without even subscribing to it:
this.sharedService.isVisibleSource.getValue(); // => true/false
Seid mehmedovic
source share