배열이 Angular 프로젝트에서 하나의 객체 만 가져 오는 이유는 무엇입니까?

Nov 25 2020

저는 League of Legends API로 작업하고 있으며, 그들이 가져 오는 챔피언 json과 더 구체적입니다.

Angular로 만든이 서비스가 있습니다.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
}

@Injectable({
  providedIn: 'root'
})
export class ChampionsService {

  constructor(private http: HttpClient) { }

  getChampions(){
    return this.http.get('http://ddragon.leagueoflegends.com/cdn/10.23.1/data/es_ES/champion.json');
  }

}

이것은 내 .ts 파일입니다.

import { Component, OnInit } from '@angular/core';
import {ChampionsService } from '../../services/champions.service';

@Component({
  selector: 'app-champions',
  templateUrl: './champions.component.html',
  styleUrls: ['./champions.component.css']
})

export class ChampionsComponent implements OnInit {

  public champions;
  public arrayChampions;
  
  
  constructor(private championsService:ChampionsService) { }

  ngOnInit(): void {
    this.getAllChampions();
  }

  getAllChampions(){
    this.championsService.getChampions().subscribe(
      data => { this.champions = data, 
        this.arrayChampions = Object.entries(this.champions.data).map(([k,v]) => ({ [k]:v })),
        this.ArrayIterator(); 
      },
      err => {console.error(err)},
      () => console.log("Champions cargados")
    );
  }

  ArrayIterator() {
    let IteratableArray = Array();
    for (let item of Object.keys(this.arrayChampions[0])) {
      var eventItem = Object.values(this.arrayChampions[0]);
      IteratableArray.push(eventItem);
    }
    this.arrayChampions = IteratableArray[0];
  }
}

그리고 이것은 html입니다.

<p>champions works!</p>
{{arrayChampions | json}}
 <!-- Cards -->
<div *ngFor="let arrayChampion of arrayChampions" class="card mb-3">
    <div class="card-header">
    </div>
    <div class="card-body">
        <blockquote class="blockquote mb-0">
            <a class="text-decoration-none">{{arrayChampion.id}}</a>
        </blockquote>
    </div>
    <div class="card-footer">
    </div>
</div>

보시다시피 var "arrayChampions"는 내가 이해하는대로 모든 챔피언을 가져와야 할 때 첫 번째 챔피언 (Atrox) 만 가져옵니다 (나는 javascript 및 Angular를 처음 사용합니다).

답변

SelakaNanayakkara Nov 26 2020 at 05:10

귀하의 예에 따라 여기에서 생성하고 stackblitz를 작성 arrayChampions했으며 그 값에 대해 전체를 반복했습니다.

여기 에서 작동하는 stacblitz를 찾으 십시오.

샘플 HTML :

<hello name="{{ name }}"></hello>
<!-- {{this.products |json}} -->
<ul>
    <li *ngFor="let champ of products | keyvalue">
        <label style="font-size: 20px;font-weight: bold;color: red;">
      {{champ.key}}
    </label>
        <ul *ngFor="let item of champ.value | keyvalue">
            <li>
                {{item.key}} : {{item.value}}
                <ul *ngFor="let sub of item.value | keyvalue">
                    <li>
                        {{sub.key}} : {{sub.value}}
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

component.ts 샘플 :

import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { map, catchError, tap } from "rxjs/operators";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  apiURL: string =
    "https://ddragon.leagueoflegends.com/cdn/10.23.1/data/es_ES/champion.json";
  name = "Angular";
  products = [];

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    this.getChamp();
  }

  getChamp() {
    this.httpClient.get(this.apiURL).subscribe((data: any) => {
      this.products = data.data;
      Object.keys(data.data).map((key: any, obj: any) => obj[key]);
    });
  }
}