2

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

1 Answer 1

8

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

4 Comments

Awesome, Thank You!
Glad I could help :)
By the way, lets say i have a loading component, how can i use that while waiting for the data?
How to check if the data is returned by the Observable or data is empty before looping or unwrapping the observable??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.