Thishan Dharmakeerthi
Thishan Dharmakeerthi

Reputation: 83

How to use async pipe with arrays in new Angular 17?

Suppose i have this promise in my component class.

testAsyncNumber = new Promise(
  (res,rej)=>{
    setTimeout(()=>{res([1,2,3,4,5])
  },2000);
});

In view template i need to get data using async pipe. I tried following approach.

<div>
  @for (number of (testAsyncNumber | async); track number) {
    {{ number }}
  } @empty {
    Empty list of users
  }
</div> 

But this doesn't work. How to overcome with this issue?

Upvotes: 2

Views: 3994

Answers (2)

Chellappan வ
Chellappan வ

Reputation: 27471

By default, TypeScript infers the type of the following Promise as Promise<unknown>. That's why you are getting an error. If you add explicit typing, it will resolve the issue:

testAsyncNumber:  Promise<Array<number>> = new Promise((res, rej) => {
    setTimeout(() => {
      res([1, 2, 3, 4, 5]);
    }, 2000);
});

OR

you can disable type checking on testAsyncNumber by adding $any function

<div>
  @for (number of $any(testAsyncNumber | async); track number) {
    {{ number }}
  } @empty {
    Empty list of users
  }
</div> 

Upvotes: 2

Pawel Twardziak
Pawel Twardziak

Reputation: 804

You might need to utilize RxJs more:

See this on stackblitz

TS variable:

  testAsyncNumber = from(
    new Promise<number[]>((res) => {
      setTimeout(() => {
        res([1, 2, 3, 4, 5]);
      }, 2000);
    })
  ).pipe(startWith([-1]));

HTML:

<div>
  @for (number of (testAsyncNumber | async); track number) {
    {{ number }}
  } @empty {
    Empty list of users
  }
</div>

Upvotes: 1

Related Questions