【问题标题】:Access Json data through external API in Angular using HttpClient使用 HttpClient 在 Angular 中通过外部 API 访问 Json 数据
【发布时间】:2018-05-31 00:09:03
【问题描述】:

我是角度的初学者。我正在尝试从外部 API 获取数据。我在控制台上成功获取了数据,但是当我尝试在屏幕上呈现它时,我收到如下错误。 注意:我使用的是 Angular 版本 5.2.10 和 CLI 版本 1.7.4。我正确使用了所有的导入,我也尝试了很多论坛。提前致谢。

这是我的服务类:

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {TeamData} from "./team-data";

const httpOptions = {
headers: new HttpHeaders({ 'X-Auth-Token': 
'62121c4f783e487fbc0785830af63bf4' })
};
@Injectable()
export class TeamService {

constructor(private http: HttpClient) {
 }

getTeams() : Observable <TeamData[]> {
var urlPrefix = "http://api.football-data.org/v1/competitions/424/teams;
return this.http.get<TeamData[]>(urlPrefix, httpOptions);
}
}

组件类:

import { Component, OnInit } from '@angular/core';
import { Team } from '../Team';
import { TeamService } from '../Team.service';
import {TeamData} from "../team-data";

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


export class ParentComponent implements OnInit {

teamData : TeamData[];
teams: Team;
constructor(private teamService: TeamService) { }

ngOnInit() {
   this.loadTeams();
}

loadTeams(){
   this.teamService.getTeams().subscribe(data =>{
   console.log(data);
   this.teamData = data;
})
}
}

模板文件

<p>Teams</p>
<div class="container">
<div class="table-responsive" *ngFor="let team of teamData">
<p>{{team.count}}</p>
<p>{{team.links}}</p>
<div *ngFor="let t of team.teams">
  <table class="table table-hover">
    <thead>

    <th>Team Name</th>
    <th>Short Name</th>
    <th>Market Value</th>
    <th>Logo</th>
    </thead>
    <tbody>
    <tr >
      <td>{{t.name}}</td>
      <td>{{t.shortName}}</td>
      <td>{{t.squadMarketValue}}</td>
      <td><img src = {{t.crestUrl}} alt = "logo"></td>
    </tr>
    </tbody>
  </table>
</div>
</div>
</div>

JSON API:http://api.football-data.org/v1/competitions/424/teams

类文件

import {Link} from "./link";
export class Team {
constructor(public links : Link[], public name: string, public code: string, 
            public shortName: string,public squadMarketValue: string,
            public crestUrl:string){}
}

import {Link} from "./link";
import {Team} from "./team";
export class TeamData {
constructor(public links:Link[], public count : number, public teams: 
            Team[]){}
}

import {Href} from "./href";
export class Link {
    constructor(link: Href[]){}
}

export class Href {
constructor(public href: any){}
}

错误信息:

ParentComponent.html:4 ERROR Error: Cannot find a differ supporting object 
'[object Object]' of type 'object'. NgFor only supports binding to 
Iterables 
such as Arrays.
at NgForOf.ngOnChanges (common.js:2579)
at checkAndUpdateDirectiveInline (core.js:12407)
at checkAndUpdateNodeInline (core.js:13935)
at checkAndUpdateNode (core.js:13878)
at debugCheckAndUpdateNode (core.js:14771)
at debugCheckDirectivesFn (core.js:14712)
at Object.eval [as updateDirectives] (ParentComponent.html:4)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697)
at checkAndUpdateView (core.js:13844)
at callViewAction (core.js:14195)

【问题讨论】:

    标签: json angular


    【解决方案1】:

    错误是您设置数据并循环打印所有团队的位置。

    1- 在团队服务中,响应是 JSON Object {} 类型而不是 JSON Array,因此您需要从

    更改转换类型
    <TeamData[]>  
    

     <TeamData> or any.
    

    2- 获取数据后,您将 JSON 对象响应分配给 JSON 数组变量。

    3- 在表格中,您应该为每个团队创建一个新行,而不是为包括表格在内的整个 div,所以在这里您需要遍历团队。

    4- 在 html 模板中,您不必循环那么多,只需删除所有循环,因为它们是不必要的。

    【讨论】:

      【解决方案2】:

      API 返回一个对象,而不是一个数组。

      {
        "_links": {},
        "count": 24,
        "teams": Array[24][]
      }
      

      这应该可以正常工作:

      <p>Teams</p>
      <div class="container">
          <div class="table-responsive" *ngIf="teamData">
            <p>{{teamData.count}}</p>
            <p>{{teamData.links}}</p>
            <div *ngFor="let t of teamData.teams">
              <table class="table table-hover">
                <thead>
                  <th>Team Name</th>
                  <th>Short Name</th>
                  <th>Market Value</th>
                  <th>Logo</th>
                </thead>
                <tbody>
                <tr >
                  <td>{{t.name}}</td>
                  <td>{{t.shortName}}</td>
                  <td>{{t.squadMarketValue}}</td>
                  <td><img src = {{t.crestUrl}} alt = "logo"></td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
      </div>
      

      【讨论】:

        猜你喜欢
        • 2014-11-24
        • 2021-12-31
        • 2018-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多