行为主题Sidenav切换Angular 7材质

时间:2019-03-28 12:19:23

标签: angular angular7 angular-material-6

我正在使用角形材料,并且我已将sidenav切换按钮放置在导航栏中。我正在尝试订阅一个布尔值来切换sidenav。该布尔值将传递给子组件之一。

我的服务:

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

  }

问题是加载组件时仅预订数据一次,而更改布尔值时则不更改数据。当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>

1 个答案:

答案 0 :(得分:1)

尝试使用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>