BehaviorSubject和有条件的组件显示
问题描述:
我有这个简单的服务:BehaviorSubject和有条件的组件显示
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
等价物吗?
如何根据BehaviourSubject
值有条件地显示Component
?
答
首先,我不认为异步管道只能使用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>
答
结束将标签检查逻辑移动到Service
。现在我的Component
不需要订阅。
谢谢,不过,那将工作,然后我需要'onInit' /'onDestroy'样板un /订阅处理。 “异步”管道可以顺利工作。我正在寻找的是一个包含Service和component.html中所有逻辑的解决方案。将保持干净。 –
我真的不明白你对组件逻辑的反对。祝你好运。 – threeve