2

I have a problem with displaying Observable object in component.

My Json structure is:

{ 
  "data": [
    {
     "id": "123",
     "name": "test",
    } 
  ], 
  "pagination": null
}

So I have created interface to map this json to .ts

export interface Paginated<T>{
   data: Array<T>;
   pagination: Pagination;
}

In my component I have Observable object for this json:

 this.httpClient.get<Paginated<Event>>(`${environment.apiUrl}/events`);

And I do not have idea how to display property data which is inside Observable<Paginated> with using async pipe, because this json is not an array - it is object with two property - data and pagination so I cannot just simply use *ngFor with async pipe, because this object is not an array.

So my question is how to display in component this property data when I received Observable<Paginated> I cannot use *ngFor... how to unpack data property from this Observable<Paginated>

2 Answers 2

2

try this

response$: Observable<Paginated<Event>>;
constructor() {
  response$ = this.httpClient.get<Paginated<Event>>(`${environment.apiUrl}/events`);
}

and in your component

<li *ngFor="let dataEl of (response$ | async)?.data">{{dataEl.name}}</li>
Sign up to request clarification or add additional context in comments.

Comments

1

In case when you want to extract the value out of an observable, you can subscribe to its value in the following way:

data: Array<T> = [];

constructor(){
   this.httpClient.get<Paginated<Event>>(`${environment.apiUrl}/events`).subscribe((response) => {

      // then extract the data from response over here
      const {data, pagination} = response;

      // assign the extracted 'data' array to a component variable named data.
      this.data = data;

   });
}

And in the html template you can then use

<li *ngFor="let el of (data)">{{data.name}}</li>

Comments

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.