使用HttpClient

时间:2018-05-31 00:09:03

标签: json angular

我是棱角分明的初学者。我试图从外部API获取数据。我成功地在控制台上获取了数据,但是当我尝试在屏幕上呈现它时,我得到如下错误。 注意:我使用的是角度版本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)

2 个答案:

答案 0 :(得分:0)

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>

答案 1 :(得分:0)

错误是您设置数据和循环以打印所有团队的地方。

1-在Team Service中,响应是JSON Object {}类型而不是JSON Array,因此您需要更改

的转换类型
<TeamData[]>  

 <TeamData> or any.

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

3-在表格中,你应该为每个团队创建一个新行,而不是整个div,包括表格,所以你需要在团队中循环。

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