Reputation: 1986
Im using angular material and i have placed the sidenav toggle button in the navbar. I am trying to subscribe to a boolean value to toggle the sidenav.The boolean is to be passed to one of the child components.
My service :
import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs'
@Injectable()
export class SidenavService {
private sidenav$ : BehaviorSubject<boolean>;
constructor() {
this.sidenav$ = new BehaviorSubject<boolean>(false);
}
getData():Observable<boolean> {
return this.sidenav$.asObservable();
}
updateData(data: boolean) {
this.sidenav$.next(data);
console.log("Changed toggle",data);
}
}
Im updating the service in the navbar component like:
sidenavtoggle(){
this.toggleSidenav.emit();
this.isOpen = !this.isOpen;
console.log("IS OPEN",this.isOpen);
this.sidenavService.updateData(this.isOpen);
};
}
I have injected the service and gave it in the providers for the component. Im subscribing to the observable in the child component sidebar component like:
constructor(private sidenavService:SidenavService) {
this.prepareNavItems();
this.subsciption=this.sidenavService.getData().subscribe(data=>{
console.log("RECEIVED DATA",data);
this.isExpanded=data;
});
}
The problem is that the data is subscribed only once when the component is loaded,and not changing when the boolean value is changed.HOw do i continuosly listen to changes in the boolean when updateData() is called?
HTML :
<mat-nav-list >
<div class="side-bar-btn" [ngClass]="{'is-active': toggle}" (click)="clickEvent($event)">
<div class="side-bar-btn-box">
<div class="side-bar-btn-inner"></div>
</div>
</div>
<mat-list-item *ngFor="let navItem of navItems" routerLinkActive="sidebarlinkactive" routerLink="{{navItem.link}}" >
<a routerLinkActive="active">
<mat-icon mat-list-icon>{{navItem.icon}}</mat-icon>
<div matLine *ngIf="isExpanded">{{navItem.text}}</div>
</a>
</mat-list-item>
</mat-nav-list>
Upvotes: 2
Views: 2097
Reputation: 1605
try to use async
pipe and also i have modified to your code some
import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs'
@Injectable()
export class SidenavService {
private sidenavSource$ = new BehaviorSubject<boolean>(false);
sidenav$ = this.sidenavSource$.asObservable();
updateData(data: boolean) {
this.sidenavSource$.next(data);
console.log("Changed toggle",data);
}
}
In your HTML use async pipe
constructor(public sidenavService: SidenavService) {} //make the service public
<div matLine *ngIf="sidenavService.sidenav$ | async">{{navItem.text}}</div>
<button (click)="sidenavService.updateData(true)">open</button>
<button (click)="sidenavService.updateData(false)">close</button>
Upvotes: 3