2

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?

3
  • 1
    What result do you get? and What behavior do you expect? Commented Jan 22, 2024 at 7:15
  • 1
    "doesn't work" is the most unhelpful symptom. Please expand Commented Jan 22, 2024 at 7:32
  • I didn't compile. Somehow with the provided answers i managed to get the data. For your reference, this was the error message i got. "[ERROR] NG8: Type '{}' must have a '[Symbol.iterator]()' method that returns an iterator." Commented Jan 22, 2024 at 7:44

2 Answers 2

2

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> 
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.