Angular:Ng的语法正确如果使用带有多个模板变量的异步管道? [英] Angular: Correct syntax for NgIf using async pipe with multiple template variables?

查看:87
本文介绍了Angular:Ng的语法正确如果使用带有多个模板变量的异步管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Angular,我们可以订阅Observable,然后通过执行以下操作将异步管道的结果分配给另一个变量:

With Angular, we can subscribe to an Observable and assign the result of the async pipe to another variable by doing :

    *ngIf="(data$ | async) as data; else loading"

我们可以检查多个条件:

We can check multiple conditions :

    *ngIf="(data1$ | async) && (data2$ | async); else loading"

但是,使用Angular"as"验证多个条件的正确语法是什么?关键字?

But what is the correct syntax to verify multiple conditions using Angular "as" Keyword ?

我尝试过:

    *ngIf="((data1$ | async) as data1) && ((data2$ | async) as data2); else loading"

但是我有一个问题:

Parser Error: Unexpected token &&, expected identifier, keyword, or string

推荐答案

您可以使用类似于对象的语法.

<ng-container *ngIf="{
  data1: data1$ | async,
  data2: data2$ | async
} as data">
  <div *ngIf="data.data1 && data.data2; else loading"> 
    <span>{{ data.data1 }}</span>
    <span>{{ data.data2 }}</span>
  </div>
</ng-container>
<ng-template #loading> ... </ng-template>

或更妙的是,只需创建一个将其他两个结合在一起的新Observable.

Or, even better, just create a new Observable which combines the other two.

data$ = combineLatest(data1$, data2$).pipe(map(([v1, v2]) => v1 && v2));

比,只是

<div *ngIf="data$ | async; else loading"> 
  ...
</div>
<ng-template #loading> ... </ng-template>

这篇关于Angular:Ng的语法正确如果使用带有多个模板变量的异步管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆