首页 > 解决方案 > 为什么数组在 Angular 项目中只带一个对象?

问题描述

我正在使用英雄联盟 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 的新手)。

标签: javascriptarraysjsonangular

解决方案


根据您的示例,我在这里创建并堆叠闪电战,它使整个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]);
    });
  }
}

推荐阅读