Reputation: 9
Trying to display data from this api. It is showing up in the console as a single object in an array.
calling api in service
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: "root",
})
export class VillagersService {
constructor(private http: HttpClient) {}
url = `http://acnhapi.com/v1/villagers/`;
getVillagers() {
return this.http.get(this.url);
}
}
component where i want to put objects from api into an array
import { Component, OnInit } from "@angular/core";
import { VillagersService } from "src/app/services/villagers.service";
@Component({
selector: "app-main",
templateUrl: "./main.component.html",
styleUrls: ["./main.component.css"],
})
export class MainComponent implements OnInit {
villagers: any = [];
constructor(private villagerService: VillagersService) {}
ngOnInit() {
this.villagerService.getVillagers().subscribe((data: any) => {
this.villagers.push(data);
console.log(this.villagers);
});
}
}
html is currently displaying one list item that reads [object, Object]
<p>main works!</p>
<h1>Villagers</h1>
<div *ngFor="let villager of villagers">
<ul>
<li>{{ villager }}</li>
</ul>
</div>
I'm not sure how I can separate each of the objects and display as a list
Upvotes: 0
Views: 3523
Reputation: 31135
It appears the response from the API (http://acnhapi.com/v1/villagers/) is one single object with multiple nested objects. In this case you could try to use the keyvalue
pipe.
Controller
export class MainComponent implements OnInit {
villagers: any;
constructor(private villagerService: VillagersService) {}
ngOnInit() {
this.villagerService.getVillagers().subscribe((data: any) => {
this.villagers = data;
});
}
}
Template
<ng-container *ngFor="let ant of villagers | keyvalue">
{{ ant.key }}
<ng-container *ngFor="let prop of ant.value | keyvalue">
<ng-container *ngIf="prop.key !== 'name'; else nameBlock">
{{ prop.key }} - {{ prop.value }}
</ng-container>
<ng-template #nameBlock>
<ng-container *ngFor="let name of prop.value | keyvalue">
{{ name.key }} - {{ name.value }}
</ng-container>
</ng-template>
</ng-container>
</ng-container>
Upvotes: 2