Не удается получить данные с помощью Angular HttpClient из API, который возвращает ответ JSON, содержащий массив - PullRequest
0 голосов
/ 10 марта 2020

Я пытаюсь нажать этот API, а затем отобразить все названия команд в шаблоне ионного / angular проекта. Я новичок в ioni c и начинаю с angular. Вот все, что я сделал до сих пор, следя за многими уроками и видео. Я подозреваю, что моя проблема в том, что json возвращает объект с результатами, а затем массив команд. Но я не знаю, как двигаться дальше.

data.service.ts

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

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

  url = 'https://api-football-v1.p.rapidapi.com/v2/';
  auth_key = 'mrwFzF28himsh2UeUlVuf9IwWoqVp1phIUGjsn8OlRdlgNiqNe';


  constructor(private _http: HttpClient) { }

  getTeams(){
    const headers = new HttpHeaders()
            .set('X-RapidAPI-Key', this.auth_key);

    return this._http.get<Team[]>(this.url + '/teams/league/1264/teams', {headers})
  }
}

team.model.ts

export class Team {
    team_id: string;
    name:string;
    code:string;
    logo: string;
    country: string;
    is_national: string;
    founded: string;
    venue_name: string;
    venue_surface: string;
    venue_address: string;
    venue_city: string;
    venue_capacity: string;
} 

tab1.page.ts

import { Component, OnInit } from '@angular/core';
import { Team } from '../team.model';
import {DataService } from '../data.service';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {

  url = 'https://api-football-v1.p.rapidapi.com/v2/';
  auth_key = 'mrwFzF28himsh2UeUlVuf9IwWoqVp1phIUGjsn8OlRdlgNiqNe';

  teams$: Team[];

  constructor(private dataService: DataService) { 
  }

  ngOnInit() {  
    return this.dataService.getTeams()
    .subscribe(data => this.teams$ = data);
  }

}

tab1.page. html

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Tab 1
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">Tab 1</ion-title>
    </ion-toolbar>
  </ion-header>

  <div *ngFor='let team of teams$'>
    <<h2>{{team.name}}</h2>
  </div>

</ion-content>

json ответ

{
    "api":{
        "results":26,
        "teams":[
            {
                "team_id":1615,
                "name":"DC United",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1615.png",
                "country":"USA",
                "is_national":false,
                "founded":1996,
                "venue_name":"Audi Field",
                "venue_surface":"grass",
                "venue_address":"32-60 R Street South West, Buzzard Point",
                "venue_city":"Washington, District of Columbia",
                "venue_capacity":20600
            },
            {
                "team_id":1610,
                "name":"Colorado Rapids",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1610.png",
                "country":"USA",
                "is_national":false,
                "founded":1996,
                "venue_name":"Dick's Sporting Goods Park",
                "venue_surface":"grass",
                "venue_address":"6000 Victory Way, Commerce City",
                "venue_city":"Denver, Colorado",
                "venue_capacity":19734
            },
            {
                "team_id":1614,
                "name":"Montreal Impact",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1614.png",
                "country":"Canada",
                "is_national":false,
                "founded":2010,
                "venue_name":"Stade Saputo",
                "venue_surface":"grass",
                "venue_address":"4750, rue Sherbrooke Est",
                "venue_city":"Montreal, Quebec",
                "venue_capacity":20801
            },
            {
                "team_id":1609,
                "name":"New England Revolution",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1609.png",
                "country":"USA",
                "is_national":false,
                "founded":1995,
                "venue_name":"Gillette Stadium",
                "venue_surface":"artificial turf",
                "venue_address":"1388 One Patriot Place",
                "venue_city":"Foxborough, Massachusetts",
                "venue_capacity":68756
            },
            {
                "team_id":1600,
                "name":"Houston Dynamo",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1600.png",
                "country":"USA",
                "is_national":false,
                "founded":2005,
                "venue_name":"BBVA Stadium",
                "venue_surface":"grass",
                "venue_address":"2200 Texas Avenue, East End",
                "venue_city":"Houston, Texas",
                "venue_capacity":22661
            },
            {
                "team_id":1605,
                "name":"Los Angeles Galaxy",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1605.png",
                "country":"USA",
                "is_national":false,
                "founded":1995,
                "venue_name":"Dignity Health Sports Park",
                "venue_surface":"grass",
                "venue_address":"18400 Avalon Boulevard, Dominguez Hills",
                "venue_city":"Carson, California",
                "venue_capacity":30510
            },
            {
                "team_id":1596,
                "name":"San Jose Earthquakes",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1596.png",
                "country":"USA",
                "is_national":false,
                "founded":1995,
                "venue_name":"Avaya Stadium",
                "venue_surface":"grass",
                "venue_address":"1123 Coleman Avenue",
                "venue_city":"San Jose, California",
                "venue_capacity":18000
            },
            {
                "team_id":1601,
                "name":"Toronto FC",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1601.png",
                "country":"Canada",
                "is_national":false,
                "founded":2006,
                "venue_name":"BMO Field",
                "venue_surface":"grass",
                "venue_address":"170 Princes\u2019 Boulevard",
                "venue_city":"Toronto, Ontario",
                "venue_capacity":36045
            },
            {
                "team_id":1597,
                "name":"FC Dallas",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1597.png",
                "country":"USA",
                "is_national":false,
                "founded":1996,
                "venue_name":"Toyota Stadium",
                "venue_surface":"grass",
                "venue_address":"6000 Main Street",
                "venue_city":"Frisco, Texas",
                "venue_capacity":22565
            },
            {
                "team_id":1599,
                "name":"Philadelphia Union",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1599.png",
                "country":"USA",
                "is_national":false,
                "founded":2008,
                "venue_name":"Talen Energy Stadium",
                "venue_surface":"grass",
                "venue_address":"Seaport Drive",
                "venue_city":"Chester, Pennsylvania",
                "venue_capacity":19178
            },
            {
                "team_id":1598,
                "name":"Orlando City SC",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1598.png",
                "country":"USA",
                "is_national":false,
                "founded":2008,
                "venue_name":"Exploria Stadium",
                "venue_surface":"grass",
                "venue_address":"655 West Church Street",
                "venue_city":"Orlando, Florida",
                "venue_capacity":25527
            },
            {
                "team_id":1606,
                "name":"Real Salt Lake",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1606.png",
                "country":"USA",
                "is_national":false,
                "founded":2004,
                "venue_name":"Rio Tinto Stadium",
                "venue_surface":"grass",
                "venue_address":"9256 South State Street",
                "venue_city":"Sandy, Utah",
                "venue_capacity":21363
            },
            {
                "team_id":9569,
                "name":"Nashville SC",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/9569.png",
                "country":"USA",
                "is_national":false,
                "founded":2017,
                "venue_name":"Nissan Stadium",
                "venue_surface":null,
                "venue_address":"1 Titans Way, Nashville",
                "venue_city":"Nashville",
                "venue_capacity":69143
            },
            {
                "team_id":1608,
                "name":"Atlanta United FC",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1608.png",
                "country":"USA",
                "is_national":false,
                "founded":2014,
                "venue_name":"Mercedes-Benz Stadium",
                "venue_surface":"artificial turf",
                "venue_address":"1 AMB Drive North West",
                "venue_city":"Atlanta, Georgia",
                "venue_capacity":73019
            },
            {
                "team_id":1603,
                "name":"Vancouver Whitecaps",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1603.png",
                "country":"Canada",
                "is_national":false,
                "founded":1986,
                "venue_name":"BC Place Stadium",
                "venue_surface":"artificial turf",
                "venue_address":"777 Pacific Boulevard, False Creek",
                "venue_city":"Vancouver, British Columbia",
                "venue_capacity":59687
            },
            {
                "team_id":1611,
                "name":"Sporting Kansas City",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1611.png",
                "country":"USA",
                "is_national":false,
                "founded":1995,
                "venue_name":"Children's Mercy Park",
                "venue_surface":"grass",
                "venue_address":"One Sporting Way",
                "venue_city":"Kansas City, Kansas",
                "venue_capacity":21650
            },
            {
                "team_id":1613,
                "name":"Columbus Crew",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1613.png",
                "country":"USA",
                "is_national":false,
                "founded":1996,
                "venue_name":"MAPFRE Stadium",
                "venue_surface":"grass",
                "venue_address":"1 Black and Gold Boulevard",
                "venue_city":"Columbus, Ohio",
                "venue_capacity":24650
            },
            {
                "team_id":1604,
                "name":"New York City FC",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1604.png",
                "country":"USA",
                "is_national":false,
                "founded":2013,
                "venue_name":"Yankee Stadium",
                "venue_surface":"grass",
                "venue_address":"One East 161st Street, The Bronx",
                "venue_city":"New York City",
                "venue_capacity":54251
            },
            {
                "team_id":1602,
                "name":"New York Red Bulls",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1602.png",
                "country":"USA",
                "is_national":false,
                "founded":1995,
                "venue_name":"Red Bull Arena",
                "venue_surface":"grass",
                "venue_address":"Frank Rogers Boulevard South",
                "venue_city":"Harrison, New Jersey",
                "venue_capacity":26765
            },
            {
                "team_id":2242,
                "name":"FC Cincinnati",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/2242.png",
                "country":"USA",
                "is_national":false,
                "founded":null,
                "venue_name":null,
                "venue_surface":null,
                "venue_address":null,
                "venue_city":null,
                "venue_capacity":null
            },
            {
                "team_id":1595,
                "name":"Seattle Sounders",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1595.png",
                "country":"USA",
                "is_national":false,
                "founded":2007,
                "venue_name":"CenturyLink Field",
                "venue_surface":"artificial turf",
                "venue_address":"800 Occidental Avenue South",
                "venue_city":"Seattle, Washington",
                "venue_capacity":72000
            },
            {
                "team_id":1607,
                "name":"Chicago Fire",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1607.png",
                "country":"USA",
                "is_national":false,
                "founded":1997,
                "venue_name":"Soldier Field",
                "venue_surface":"grass",
                "venue_address":"1410 South Museum Campus Drive",
                "venue_city":"Chicago, Illinois",
                "venue_capacity":62493
            },
            {
                "team_id":1616,
                "name":"Los Angeles FC",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1616.png",
                "country":"USA",
                "is_national":false,
                "founded":2014,
                "venue_name":"Banc of California Stadium",
                "venue_surface":"grass",
                "venue_address":"3939 S Figueroa Street",
                "venue_city":"Los Angeles, California",
                "venue_capacity":22902
            },
            {
                "team_id":9568,
                "name":"Inter Miami",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/9568.png",
                "country":"USA",
                "is_national":false,
                "founded":2018,
                "venue_name":"Lockhart Stadium",
                "venue_surface":"grass",
                "venue_address":"5201 NW 12th Avenue \/ 1350 NW 55 Street",
                "venue_city":"Fort Lauderdale, Florida",
                "venue_capacity":20450
            },
            {
                "team_id":1617,
                "name":"Portland Timbers",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1617.png",
                "country":"USA",
                "is_national":false,
                "founded":2009,
                "venue_name":"Providence Park",
                "venue_surface":"artificial turf",
                "venue_address":"1844 SW Morrison Street",
                "venue_city":"Portland, Oregon",
                "venue_capacity":25218
            },
            {
                "team_id":1612,
                "name":"Minnesota Stars FC",
                "code":null,
                "logo":"https:\/\/media.api-sports.io\/teams\/1612.png",
                "country":"USA",
                "is_national":false,
                "founded":2010,
                "venue_name":"Allianz Field",
                "venue_surface":"grass",
                "venue_address":"400 Snelling Avenue North",
                "venue_city":"Saint Paul, Minnesota",
                "venue_capacity":19939
            }
        ]
    }
}

Ответы [ 2 ]

0 голосов
/ 10 марта 2020

ngOnInit является пустой функцией, и поэтому ничего не возвращает

- это массив, по которому вы хотите выполнить итерацию.

ngOnInit() {
    this.dataService.getTeams()
        .pipe(take(1))
        .subscribe(data => this.teams$ = data.api.teams);
}

Массив, по которому вы хотите выполнить итерацию, равен

data.api.teams

Обратите внимание, что я использовал канал под названием "take", который уничтожает подписку после завершения метода подписки. Это важно сделать, иначе у вас будут утечки памяти.

0 голосов
/ 10 марта 2020

Вы должны получить доступ к командам, возвращенным из ответа json, используя точечную запись, как показано ниже:

  ngOnInit() {  
    this.dataService.getTeams()
    .subscribe(data => this.teams$ = data.api.teams);
  }

, и теперь ваши команды $ ссылаются на команды из ответа. Теперь это должно работать.

...