Talal Tahir Malik
Talal Tahir Malik

Reputation: 175

How to loop through array inside an observable using async pipe?

I am consuming an API which returns a response like this:

case:1
requests:[reqObj1,reqObj2,reqObj3]
count:3
message:"Found requests successfully."
pagesCount:1

The Service:

listRequest(sort, records, pageNumber, queries?): Observable<any> {
    const updateQueries = this.gtn.getHeaders() as RequestOptions;
    updateQueries.params = queries;
    return this.http
      .get(globals.domain + '/team/requests/list/sortBy-' + sort + '/' + records + '/' + pageNumber + '/', updateQueries)
      .map(res => {
        this.responseData = res.json();
        return this.responseData;
      });
  }

This will return an Observable with the response object as mentioned above, I will get this observable in the component and assign it to the local observable in the component.

Component:

this.requestResponse= this.rts.listRequest(sort, records, page, this.q);

I want to iterate over the array of request which is in the observable and i am using the async pipe in my html

HTML:

    <div class="request-items-inner" *ngFor="let request of requestResponse.requests | async">
{{request.createdAt}}
</div>

but this does not display anything on the screen. And if i use *ngFor="let request of requestResponse| async" it gives an error in the console.

enter image description here

Upvotes: 2

Views: 3369

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16837

You need to unwrap the response with an 'async' pipe first, and then iterate over the requests array.

<div class="request-items-inner" *ngFor="let request of (requestResponse | async)?.requests">
  {{ request.createdAt }}
</div>

Upvotes: 8

Related Questions