Reputation: 71
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>
Upvotes: 2
Views: 1433
Reputation: 1661
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>
Upvotes: 1
Reputation: 21387
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>
Upvotes: 2