简体   繁体   English

Angular:NgIf 使用带有多个模板变量的异步管道的正确语法?

[英]Angular: Correct syntax for NgIf using async pipe with multiple template variables?

With Angular, we can subscribe to an Observable and assign the result of the async pipe to another variable by doing :使用 Angular,我们可以订阅一个 Observable 并通过执行以下操作将异步管道的结果分配给另一个变量:

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

We can check multiple conditions :我们可以检查多个条件:

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

But what is the correct syntax to verify multiple conditions using Angular "as" Keyword ?但是使用 Angular "as" 关键字验证多个条件的正确语法是什么?

I tried :我试过 :

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

But I have an issue :但我有一个问题:

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

You can use the object-like syntax.您可以使用类对象语法。

<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>

Or, even better, just create a new Observable which combines the other two.或者,更好的是,创建一个新的Observable来结合其他两个。

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

Than, just比,只是

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

You can try this:你可以试试这个:

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

  {{data.data1}}
  {{data.data2}}
</div>
<ng-template #loading>
    loading..........
 </ng-template>
</ng-container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM