行为主题 Sidenav 切换 Angular 7 Material

Behaviour Subject Sidenav Toggle Angular 7 Material

我正在使用 angular material,并且我已将 sidenav 切换按钮放置在导航栏中。我正在尝试订阅一个布尔值以切换 sidenav.The 布尔值将传递给子组件之一。

我的服务:

 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);

    }
}

我正在更新导航栏组件中的服务,例如:

  sidenavtoggle(){
    this.toggleSidenav.emit();
    this.isOpen = !this.isOpen;
    console.log("IS OPEN",this.isOpen);
    this.sidenavService.updateData(this.isOpen);

    };
  }

我已经注入服务并将其提供给组件的提供者。我正在订阅子组件侧边栏组件中的可观察对象,例如:

  constructor(private sidenavService:SidenavService) {
    this.prepareNavItems();

    this.subsciption=this.sidenavService.getData().subscribe(data=>{
      console.log("RECEIVED DATA",data);
      this.isExpanded=data;
    });

  }

问题是数据只在加载组件时被订阅一次,并且当布尔值为 changed.HOw 时数据不会改变 changed.HOw 我是否在 updateData() 时继续监听布尔值的变化 叫什么?

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>

尝试使用 async 管道,我也对您的代码进行了一些修改

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);

    }
}

在你的HTML中使用异步管道

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>