如果使用异步管道,则在单个ng上合并两个或多个(布尔)可观察对象 [英] Combine two or more (boolean) observables on single ngIf using async pipe
问题描述
没有可观察到的东西,我可以在HTML模板中写以下行:
Without observables I can write the following line in the HTML template:
<div *ngIf="(myVarA || myVarB) && myVarC !== x"></div>
如果现在所有的myVar
变量实际上都是可观察的,我该如何翻译这一行?
How do I translate this line if all myVar
variables are now actually observables?
<div *ngIf="((myVarA | async) || (myVarB | async)) && (myVarC | async) !== x">
不起作用.
在另一个问题中(将两个异步订阅放入一个Angular中* ngIf语句)可以将两个或多个可观察变量组合为一个ngIf的可能性,如
In another question (Putting two async subscriptions in one Angular *ngIf statement) the possibility to combine two or more observables into one ngIf can be achieved like
<div *ngIf="{ a: myVarA | async, b: myVarB | async } as result"></div>
但是,我看不到在随后用于评估ngIf的表达式上使用任何布尔运算符(或与此相关的任何运算符)的可能性.
However, I do not see the possibility to use any boolean operators (or any operators for that matter) on the expression that is then being used to evaluate the ngIf.
我该如何解决这个问题?请注意,我所有的Observable都在下面使用BehaviorSubject.我认为本质上我想要的是在模板内使用combineLatest
运算符.
How can I tackle this issue? Please note, all my Observables use a BehaviorSubject underneath. I think essentially what I want is to use the combineLatest
operator inside the template.
奖金:如果整个表达式的值为true,以便以后在模板中使用(如在myVarA | async as varA
中),是否有任何方法可以提取myVarA的单个值?
Bonus: Is there any way to extract the single value of myVarA if the whole expression evaluates to true for later use in the template (as in myVarA | async as varA
)?
推荐答案
使用combineLatest
怎么样?
例如:
import { combineLatest } from 'rxjs/observable/combineLatest';
import { Observable } from 'rxjs/Observable';
@Component({...})
export class FooComponent {
obs1$: Observable<bolean>;
obs2$: Observable<bolean>;
obs3$: Observable<bolean>;
constructor(){
// set observables
}
get combined$(){
return combineLatest(
this.obs1$,
this.obs2$
this.obs3$,
(one,two,three)=>(one || two) && three);
}
}
// template
<div *ngIf="combined$ | async">
检查以下小提琴以获得指导:
Check the following fiddle for guidance:
https://jsfiddle.net/uehasmb6/11/
有关combineLatest
运算符的更多信息此处
More info about the combineLatest
operator here
更新:但是,如果您仍然希望将所有逻辑保留在模板中,则可以尝试以下操作:
UPDATE: But if you still want to keep all that logic inside of the template, you could try something like:
<div *ngIf="((myVarA | async) || (myVarB | async)) && ((myVarC | async) !== x)">
但是我建议你反对这个. 良好做法.
But I would advice you against this. Keeping the HTML template as clean as possible is a good practice.
这篇关于如果使用异步管道,则在单个ng上合并两个或多个(布尔)可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!