How to check the length of an Observable array

只谈情不闲聊 提交于 2019-11-27 11:10:21
Günter Zöchbauer

You can use the | async pipe:

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

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>

A solution for .ts-Files:

     this.list.subscribe(result => {console.log(result.length)});

For Angular 4+, try this

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

While this answer is correct

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

Keep in mind that if you are using http client to call backend (in most cases you do) you will get duplicate calls to your API if you have more that one list$ | async. This is because each | async pipe will create new subscriber to your list$ observable.

This is what worked for me -

*ngIf="!photos || photos?.length===0"

I am getting my data from httpClient async.

All the other options here didn't work for me which was disappointing. Especially the sexy (list$ | async) pipe.

Basa..

Your approach here has another major issue: by leveraging the async pipe over and over in your template, you are actually kicking off that many subscriptions to the single Observable.

KAMRUL HASAN SHAHED has the right approach above: Use the async pipe once and then provide an alias for the result that you can leverage in child nodes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!