I'm trying to get the updated value from a service variable (isSidebarVisible
) which is keeps on updated by another component (header
) with a click event (toggleSidebar
).
sidebar.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SidebarService {
isSidebarVisible: boolean;
sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();
constructor() {
this.isSidebarVisible = false;
}
toggleSidebarVisibilty() {
this.isSidebarVisible = !this.isSidebarVisible
this.sidebarVisibilityChange.next(this.isSidebarVisible);
}
}
sidebar.component.ts
export class SidebarComponent implements OnInit {
asideVisible: boolean;
_asideSubscription: any;
constructor(private sidebarService: SidebarService) {
this.asideVisible = sidebarService.isSidebarVisible
this._asideSubscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
this.asideVisible = value
})
}
ngOnInit() {
}
}
header.component.ts (Where service variable is updated)
export class HeaderComponent implements OnInit {
isSidebarVisible: boolean;
_subscription: any;
constructor(private sidebarService: SidebarService) {
this._subscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
this.isSidebarVisible = value
})
}
toggleSidebar() {
this.sidebarService.toggleSidebarVisibilty()
}
ngOnInit() {
}
}
I can see the service variable value change in header.component.html
when {{ isSidebarVisible }}
but In sidebar.component.html
it always prints the default value and never listened to the changes.
Please help me fix this.