-1

我有这个简单的服务:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class HighlightsService {
  private _highlitTab: string = '';
  highlitTab$: BehaviorSubject<string> = new BehaviorSubject(this._highlitTab);

  public get tab(): string {
    return this._highlitTab;
  }

  public set tab(val: string) {
    this._highlitTab = val;
    this.highlitTab$.next(this._highlitTab);
  }
}

在我的标签中设置:

(select)="highlightsService.tab = 'show component0'

现在在我看来显示多个指令,我如何有条件地显示它们?

<app-component0 [hide]="highlightsService.highlitTab$ | async"></app-component0>
<app-component1 [show]="highlightsService.highlitTab$ | async"></app-component0>

显然这是行不通的,因为没有===. 有没有ngSwitch等价的?

如何Component根据BehaviourSubject值有条件地显示 s?

4

2 回答 2

-1

最终将选项卡检查逻辑移至Service. 现在我Component的 s 不需要订阅。

于 2016-12-15T02:52:21.373 回答
-1

首先,我认为异步管道无论如何都不能仅与 BehaviorSubject 一起使用。我会这样做:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HighlightsService {
  private _highlitTab: string = '';
  private _highlitTab$: BehaviorSubject<string> = new BehaviorSubject(this._highlitTab);
  public highlitTab$: Observable<string> = this._highlitTab$.asObservable();

  public get tab(): string {
    return this._highlitTab;
  }

  public set tab(val: string) {
    this._highlitTab = val;
    this._highlitTab$.next(this._highlitTab);
  }
}

_highlitTab变量的值也值得怀疑,因为您可以在服务中使用this._highlitTab$.getValue().

现在,在你的组件中,你注入HighlightsService你似乎已经在做的事情,并订阅它,可能在ngOnInit()

this.highlightsService.highlitTab$
    .filter(value => value)
    .subscribe(value => this.hightlitTab = value);

过滤器行确保您不会获得空值(初始化值)。这可能不是您想要的行为。

最后,您现在可以通过将其与更新的本地值进行比较来显示或隐藏您想要的任何选项卡highlitTab。如果是我,我可能只是将highlitTab值传递给子组件,该组件可以决定是否显示自己。

<child-component0 [highlitTab]='hightlitTab'></child-component>
于 2016-12-14T16:33:31.550 回答