【问题标题】:Why array only brings one object in Angular project?为什么数组在 Angular 项目中只带一个对象?
【发布时间】:2020-11-25 22:18:00
【问题描述】:

我正在使用英雄联盟 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>

如您所见,变量“arrayChampions”只带来了第一个冠军(Atrox),而它应该带来我所理解的所有冠军(我是 javascript 和 Angular 的新手)。

【问题讨论】:

  • 我认为你的 ArrayIterator 有问题,我在这里在 stackblizt 中做了一个简单的测试 => stackblitz.com/edit/… ,它工作正常

标签: javascript arrays json angular


【解决方案1】:

根据您的示例,我在这里创建并堆叠闪电战,它使整个 arrayChampions 迭代其值。

请找到工作的 stacblitz here

示例 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>

示例组件.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]);
    });
  }
}

【讨论】:

  • 谢谢伙计。我应用了你的代码并且它有效。你能告诉我明白的解释吗?
  • 当然.. 这行中发生的事情Object.keys(data.data).map((key: any, obj: any) =&gt; obj[key]); 具有魔力。它从 API 调用中获取你的 heros 响应,并迭代每个对象,并通过其键获取每个对象的值,并将其分配到另一个数组中,你的模板可以对其进行迭代。那就是在那条线上发生的事情。如果可能的话,我非常感谢对这两个答案的支持。乐于助人
猜你喜欢
  • 2021-11-11
  • 2023-04-06
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多