Programing

Observable 배열의 길이를 확인하는 방법

lottogame 2020. 9. 13. 11:35
반응형

Observable 배열의 길이를 확인하는 방법


내 Angular 2 구성 요소에는 Observable 배열이 있습니다.

list$: Observable<any[]>;

내 템플릿에는

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

그러나 Observable 배열의 경우 list $ .length는 작동하지 않습니다.

최신 정보:

그것은 그 보인다 길이는? | (비동기 목록을 $) : 우리에게 길이를 제공하지만, 코드 아래 여전히 작동하지 않습니다

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

누구든지 Observable 배열의 길이를 확인하는 방법을 안내해 주시겠습니까?


| async파이프 를 사용할 수 있습니다 .

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

업데이트-Angular 버전 6 :

CSS 스켈레톤을로드하는 경우 이것을 사용할 수 있습니다. 배열에 항목이 없으면 CSS 템플릿이 표시됩니다. 데이터가 있으면 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>

.ts-Files에 대한 솔루션 :

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

Angular 4+의 경우 이것을 시도하십시오

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

이 대답은 정확하지만

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


Can be shortened as well:

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

Just use the exclamation mark before the parenthesis.

참고URL : https://stackoverflow.com/questions/38057537/how-to-check-the-length-of-an-observable-array

반응형