0

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

1
  • Is the API returning an array? If so, you should be adding to the villagers array like this: this.villagers.push(...data); Commented Jun 15, 2020 at 21:15

1 Answer 1

2

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

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.