Struggling to fetch information with Angular HttpClient from an API that sends back a JSON response with an array

As a beginner in Ionic and Angular, I am attempting to call an API and then showcase the team names within the template of my project. Despite following numerous tutorials and videos, I seem to be stuck as the JSON response returns an object with results followed by an array of teams. I am unsure how to proceed from here.

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 Response

{
    "api":{
        "results":26,
        "teams":[
            ...
        ]
    }
}

Answer №1

To retrieve the teams from a JSON response, make sure to use dot notation as shown in the code snippet below:

  ngOnInit() {  
    this.dataService.fetchTeams()
    .subscribe(response => this.teamsList$ = response.teams.data);
  }

Now that your teamsList$ variable is set to reference the teams data from the response, everything should work smoothly.

Answer №2

ngOnInit is a function with no return value.

This is the array you'll be iterating through.

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

The array being iterated through is

data.api.teams

It's worth noting that I included a pipe called "take" to properly end the subscription after completion of the subscribe method. This prevents memory leaks from occurring.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to access the selectedIndex and handle click events for select options in Angular4

Initially, my aim was to get the selectedIndex and then retrieve the selected data model, but I discovered that I could directly access the selected data model in Angular2 RC2 by following this link: Angular2 RC2 Select Option selectedIndex. However, I e ...

Tips for updating collection-repeat list when a value is modified

On my view, I have a collection-repeat element displaying a large amount of data, and I want to dynamically change its sorting based on the user's selection from a dropdown menu. Even though the $scope.isAscending variable is being updated correctly, ...

Navigating route parameters in Angular Universal with Java

I am currently developing a web application using Angular 5 with Server Side Rendering utilizing Angular Universal for Java. The project repository can be found here. One of the challenges I am facing is with a parameterized route defined in Angular as /pe ...

Experiencing a compilation issue while attempting to apply the class-transformer

Encountering an issue while working with a basic example that involves class-transformer. error TS1240: Unable to resolve signature of property decorator when called as an expression. Argument of type 'ClassFieldDecoratorContext<Root, Project[]> ...

You may encounter an error stating "Property X does not exist on type 'Vue'" when attempting to access somePropOrMethod on this.$parent or this.$root in your code

When using VueJS with TypeScript, trying to access a property or method using this.$parent.somePropOrMethod or this.$root.somePropOrMethod can lead to a type error stating that Property somePropOrMethod does not exist on type 'Vue' The defined i ...

Creating unique custom 404 error pages for specific sub-directories within NextJS using the App Router Structure

Having trouble with my custom 404 error page (= not-found.tsx) files. I have two of them, one within app/(paths) and another within app/(paths)/(jobs)/jobs/(cats). The issue is that the first not-found file should render when a user visits url example myap ...

Comparing ngrx's createSelector method with Observable.combineLatest

Exploring the custom selectors from ngrx has left me in awe of their capabilities. Considering the example of using books for selectedUser, I find myself questioning the need for a custom selector like: export const selectVisibleBooks = createSelector(se ...

Invoke a function within an Angular component that is passed in as a parameter

Is it possible to invoke a function using a string in JavaScript? I have a scenario where I receive a string as the function name, and I need to call and run that function. However, my current code is not working as expected. Below is the code snippet I ...

What is the best way to import modules in Typescript/Javascript synchronously during runtime?

I have a Typescript class where I am attempting to perform a synchronous import, however, the import is being executed asynchronously. My code snippet looks like this: --------------100 lines of code-------------------- import('../../../x/y/z') ...

Difficulty accessing files with Angular deployment in Nginx through Docker

Recently, I delved into the world of Docker and Nginx in an attempt to deploy my angular application. Unfortunately, I encountered a perplexing issue. Upon executing the command: npm run build, I noticed that my index.html contained script references as f ...

Angular compilation alerted about a missing export: "ɵɵdefineInjectable was not located within '@angular/core'

I'm having an issue while trying to run my Angular application. The error message related to the "ngx-mqtt": "^6.6.0" dependency keeps popping up even though I have tried changing the versions multiple times. I am using CLI 6.2.9 and cannot seem to re ...

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

Tips for resolving TypeScript object undefined error when utilizing object of model classes

I encountered an issue while working with an object of a class that retrieves data from an API. When trying to access this object in the HTML, I'm receiving error TS2532. Here is the relevant code snippet-- export interface TgtInfo{ Mont ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Display highlighted option in material dropdown

Is there a way to display the selected value on the label in this code? Thanks for any help! ...

What advantages does using a predicate as a return type offer over a simple boolean?

Recently, I stumbled upon the concept of user-defined typeguards while perusing through this enlightening article: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards One intriguing example presented in the aforementi ...

The p-calendar feature is experiencing compatibility issues with Internet Explorer, Edge, and Firefox

While I've had success using primeng p-calendar on Google Chrome, I've encountered an issue where the date-picker does not open upon clicking the text box on other browsers. Below is the snippet of HTML code I utilized: <p-calendar [(ngModel ...

Issue with starting @mauron85/cordova-plugin-background-geolocation on Ionic 5 and Angular 9 platform

I'm facing a challenge with integrating the background geolocation plugin into my app. Here is the documentation link for reference: https://ionicframework.com/docs/native/background-geolocation Here's the snippet of my code that initiates the p ...

Accessing the constants and state of child components within a parent component in React

I've created a MUI TAB component that looks like this <Box sx={{ width: "100%" }}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label ...