Angular 6: The Promise<any> is incompatible with the LeagueTable type

Recently delving into Angular and attempting to retrieve JSON League Table data from the API, I encountered an error message stating Type 'Promise' is not assignable to type 'LeagueTable'.

leaguetable.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators/map';

  const baseUrl = 'http://api.football-data.org/v1';

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

 constructor(private http: HttpClient) { }

  getLeagueTable() {
    let headers = new HttpHeaders();
    headers = headers.set('X-Auth-Token', 'apikey');
    return this.http.get(baseUrl +'/competitions/445/leagueTable', { headers: headers })
   .pipe(map((res: Response) => res.json()));
  }

}

leaguetable.component.ts

import { Component, OnInit } from '@angular/core';
import { LeagueTable } from '../league-table';
import { LeaguetableService } from '../leaguetable.service';

@Component({
  selector: 'app-leaguetable',
  templateUrl: './leaguetable.component.html',
  styleUrls: ['./leaguetable.component.css']
})
export class LeaguetableComponent implements OnInit {

  leagueTable: LeagueTable;

  constructor(private leagueTableService: LeaguetableService) { }

  ngOnInit() {
    this.getLeagueTable();
  }

  getLeagueTable() {
    this.leagueTableService.getLeagueTable().subscribe(leagueTable => this.leagueTable = leagueTable);
  }
}

league-table.ts

export class LeagueTable {
  leagueCaption: string;
  matchday: number;
  standing: ({ 
    rank: number;
    team: string;
    teamId: number;
    playedGames: number;
    crestURI: string;
    points: number;
    goals: number;
    goalsAgainst: number;
    goalDifference: number;
  })
}

Seeking guidance on why this issue is occurring, any assistance is highly appreciated!

EDIT: Attached class file for enhanced clarity.

Answer №1

When looking to make changes to my response, it appears that you are attempting to assign the promise returned by res.json() to leagueTable, which is a LeagueTable object. If your intention is to return a promise, you should use then() within your subscribe block to handle the value assignment. I recommend trying to eliminate the pipe and map functions, and simply return the observable, subscribing to it as usual.

Same sentiments as the previous comments:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators/map';

  const baseUrl = 'http://api.football-data.org/v1';

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

 constructor(private http: HttpClient) { }

  getLeagueTable() {
    let headers = new HttpHeaders();
    headers = headers.set('X-Auth-Token', 'apikey');
    // Just returning the observable from get()
    return this.http.get(baseUrl +'/competitions/445/leagueTable', { headers: headers });
  }

}

Answer №2

Give this method a try

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators/map';

  const baseUrl = 'http://api.football-data.org/v1';

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

 constructor(private http: HttpClient) { }

  fetchLeagueData() {
    let headers = new HttpHeaders();
    headers = headers.set('X-Auth-Token', 'apikey');
    // Returning the observable from get()
    return this.http.get(baseUrl +'/competitions/445/leagueTable', { headers: headers })
    .map(res => res.json());
  }

}



import { Component, OnInit } from '@angular/core';
import { LeagueTable } from '../league-table';
import { LeaguetableService } from '../leaguetable.service';

@Component({
  selector: 'app-leaguetable',
  templateUrl: './leaguetable.component.html',
  styleUrls: ['./leaguetable.component.css']
})
export class LeaguetableComponent implements OnInit {

  leagueTable: LeagueTable;

  constructor(private leagueTableService: LeaguetableService) { }

  ngOnInit() {
    this.displayLeagueTable();
  }

  displayLeagueTable() {
    this.leagueTableService.fetchLeagueData().subscribe(leagueTable => {
      console.log(leagueTable);
      this.leagueTable = leagueTable
    });
  }
}

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

When set to synchronize:true in Typeorm, any changes to an entity will result in the many-to

As a newcomer to typeorm, I've encountered a peculiar issue with the synchronize: true setting in my ormconfig.js. Whenever I make changes to an entity with a Many-to-Many relationship, any data present in the join table prior to the entity modificati ...

Creating multiple copies of a form div in Angular using Typescript

I'm attempting to replicate a form using Angular, but I keep getting the error message "Object is possibly 'null'". HTML: <div class="form-container"> <form class="example"> <mat-form-field> ...

Testing Angular: Inability to achieve full code coverage for Ternary branch in unit testing

Currently, I am attempting to test a ternary branch that utilizes the window.location property. @Injectable() export class ABCService { private hostUrl = (window.location.host.indexOf('localhost') > -1) ? 'example.com' : window.lo ...

The functionality of Angular is not compatible with a mobile network connection

Recently, I noticed that my Angular 6 application hosted on my server with SSL and HTTPS protocol loads quickly on my computer but is extremely slow on my mobile phone, taking about 3-4 minutes to fully load. I conducted network profiling using Chrome, bu ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...

Looking for a solution to resolve the issue "ERROR TypeError: Cannot set property 'id' of undefined"?

Whenever I attempt to call getHistoryData() from the HTML, an error message "ERROR TypeError: Cannot set property 'id' of undefined" appears. export class Data { id : string ; fromTime : any ; toTime : any ; deviceType : string ...

After sending an HTTP Post request in Angular 5, users are required to click in order

Currently, I am in the process of developing an Angular 5 component that integrates "ngx-file-drop" and "ngx-spinner" modules. Upon uploading a file through my API, an issue arises. Despite the successful upload of the file and the console.log message disp ...

Is there a way to make a peer dependency optional in a project?

In the process of developing module A, I have implemented a feature where users can choose to inject a Winston logger into my module. As a result, winston becomes a peer dependency. However, when attempting to include module A in another module without th ...

Working with Typescript and JSX in React for event handling

I'm currently facing an issue with updating the state in a React component I'm developing using TypeScript (React with Addons 0.13.3, Typescript 1.6.0-dev.20150804, definition file from ). /// <reference path="react/react-addons.d.ts" /> i ...

What is the best way to retrieve an array that was created using the useEffect hook in React?

Utilizing the power of useEffect, I am fetching data from two different APIs to build an array. My goal is to access this array outside of useEffect and utilize it in the return statement below to render points on a map. However, when trying to access it ...

Encountering NullInjectorError while testing Angular unit tests: DatePipe provider is missing

I have been working on implementing unit tests for a service that has dependencies injected from two other services. One of the injected services utilizes the Angular DatePipe, so I am utilizing the Angular TestBed to automate the process. However, when ru ...

Is it considered poor practice in TypeScript to manually set the type when the type inference is already accurate?

Is it necessary to explicitly set the variable type in TypeScript when it is inferred correctly? For example: const add = (a: number, b: number) => a + b; const result = add(2, 3); // Or should I explicitly declare the return value type? const add = ...

Guide on importing a markdown file (.md) into a TypeScript project

I've been attempting to import readme files in TypeScript, but I keep encountering the error message "module not found." Here is my TypeScript code: import * as readme from "./README.md"; // I'm receiving an error saying module not found I als ...

How can I eliminate the immediate forward slash (/) following a hash (#) in an Angular application

After configuring my angular 8 app routing with {useHash:true}, I encountered an issue. Whenever I open a URL in the browser, such as https://localhost:4200/#/todo https://localhost:4200/#/todo/12 I do not want that additional "/" immediately after "#". ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...

The parameters provided in TypeScript do not align with any signature of the call target

In JavaScript, a function can be called with any number of parameters. If a parameter is not passed, it will default to undefined without causing an error. Below is a code snippet for reference: function test(a,b){ if(b){console.log(b)} else{console ...

Tips for Implementing Cache Busting in Angular Universal

Is there a way to execute cache busting in Angular Universal? I attempted to run the command npm run build:ssr --output-hashing=all but it did not make any changes. PACKAGE.json "scripts": { "ng": "ng", "start": "ng serve", "build": "ng bui ...

What is the Angular2 equivalent of the AngularJS $routeChangeStart event?

During our time working with AngularJS, we utilized the $routeChangeStart/End event in the $rootScope to monitor changes in the route object. What is the equivalent method for monitoring route changes in Angular2? How can we achieve the same functionality ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...