如何检查 Observable 数组的长度 [英] How to check the length of an Observable array

查看:29
本文介绍了如何检查 Observable 数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Angular 2 组件中,我有一个 Observable 数组

list$: Observable;

在我的模板中

未找到记录.

<div *ngIf="list$.length>0"><ul><li *ngFor="let item of list$ | async">item.name</li>

但是 list$.length 不适用于 Observable 数组.

更新:

似乎 (list$ | async)?.length 给了我们长度,但下面的代码仍然不起作用:

长度:{{(list$ | async)?.length}}<div *ngIf="(list$ | async)?.length>0"><ul><li *ngFor="let item of (list$ | async)">{{item.firstName}}

谁能指导我如何检查 Observable 数组的长度.

解决方案

您可以使用|异步管道:

<div *ngIf="(list$ | async)?.length==0">未找到记录.</div>

更新 - 2021 年 2 月 17 日

<ul *ngIf="(list$| async) as list;其他加载"<li *ngFor="let listItem of list">{{ listItem.text }}<ng-template #loading><p>无数据时显示,等待Api</p><加载组件></加载组件></ng-模板>

更新 - Angular 版本 6:

如果你正在加载一个 css 骨架,你可以使用它.如果数组没有项目,它将显示 css 模板.如果有数据则填写ngFor.

<ul *ngIf="(list$| async)?.length >0;其他加载"<li *ngFor="let listItem of list$|异步">{{ listItem.text }}<ng-template #loading><p>无数据时显示,等待Api</p><加载组件></加载组件></ng-模板>

In my Angular 2 component I have an Observable array

list$: Observable<any[]>;

In my Template I have

<div *ngIf="list$.length==0">No records found.</div>

<div *ngIf="list$.length>0">
    <ul>
        <li *ngFor="let item of list$ | async">item.name</li>
    </ul>
</div>

But list$.length doesn't work with in case of Observable array.

Update:

It seems that (list$ | async)?.length gives us the length but the below code still doesn't work:

<div>
    Length: {{(list$ | async)?.length}}
    <div *ngIf="(list$ | async)?.length>0">
        <ul>
            <li *ngFor="let item of (list$ | async)">
                {{item.firstName}}
            </li>
        </ul>
    </div>
</div>

Can anyone please guide how do I check length of Observable array.

解决方案

You can use the | async pipe:

<div *ngIf="(list$ | async)?.length==0">No records found.</div>

Update - 2021-2-17

<ul *ngIf="(list$| async) as list; else loading">
   <li *ngFor="let listItem of list">
      {{ listItem.text }}
   </li>
</ul>

<ng-template #loading>
  <p>Shows when no data, waiting for Api</p>
  <loading-component></loading-component>
</ng-template>

Update - Angular Version 6:

If you are loading up a css Skeleton you can use this. If the array has no items it will display the css template. If there is data then fill out the ngFor.

<ul *ngIf="(list$| async)?.length > 0; else loading">
   <li *ngFor="let listItem of list$| async">
      {{ listItem.text }}
   </li>
</ul>

<ng-template #loading>
  <p>Shows when no data, waiting for Api</p>
  <loading-component></loading-component>
</ng-template>

这篇关于如何检查 Observable 数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆