Struggling to retrieve JSON data from a REST API in Angular2

I attempted to implement the instructions provided on angular.io (Tour of Heroes) by making a GET request to a locally deployed springboot application. However, I encountered an issue where I was unable to retrieve the list of heroes on my Angular app when using a different URL than the one suggested in the tutorial. For reference, the tutorial uses an in-memory-dataservice which works as expected.

Here is the JSON response from my API:

[{"id":11,"name":"Mr. Nice"},{"id":12,"name":"Narco"}]

The code I have implemented differs only in terms of the URL:

private heroesUrlmain = 'http://localhost:8080/heros.json';  // URL to web api

private headers = new Headers({'Content-Type': 'application/json'});

constructor(private http: Http) { }

getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrlmain)
  .toPromise()
  .then(response => response.json().data as Hero[])
  .catch(this.handleError);
 }

For this service, I have imported only the essential modules:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
import 'rxjs/Rx';

I would appreciate any guidance or advice on what changes I need to make in order for the Angular app to successfully retrieve data from the API using the GET method.

Below is the @Component code:

@Component Code:

import { Component } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { Router } from '@angular/router';

import { OnInit } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'my-heroes',
  templateUrl: 'heroes.component.html',
  styleUrls: [ 'heroes.component.css' ]
})

export class HeroesComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(
    private router: Router,
    private heroService: HeroService) { }

  getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

  ngOnInit(): void {
    this.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }    
}  

Template :

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)"
      [class.selected]="hero === selectedHero">
    <span class="badge">{{hero.id}}</span>
    <span>{{hero.name}}</span>
    <button class="delete"
            (click)="delete(hero); $event.stopPropagation()">x</button>
  </li>
</ul>
<div *ngIf="selectedHero">
  <h2>
    {{selectedHero.name | uppercase}} is my hero
  </h2>
  <button (click)="gotoDetail()">View Details</button>
  <label>Hero name:</label> <input #heroName />
  <button (click)="add(heroName.value); heroName.value=''">
    Add
  </button>
</div>

The handleError code requested reads as follows:

private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
  }

Answer №1

The data you are handling is in JSON format and structured as an array. This array does not contain a field called data, so trying to access

response => response.json().data as Hero[]
will result in an error.

To properly retrieve the JSON data as an array of heroes, simply use

response => response.json() as Hero[]

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

unconventional TypeScript interface/class properties

Currently, I am involved in a project called JSON-Schema-faker, where we utilize the TypeScript interface shown below: interface IGeneratorSchema { faker?: any; chance?: any; } to define objects like: { "faker": "name.findName" } or: { "chance ...

Using ng2 to retrieve an object from an HttpGet service

I'm currently facing an issue with retrieving JSON data from my WebAPI. Every time I attempt to use the returned object in my component, it displays as undefined. The goal is to showcase student and course data on the homepage of my website. Currentl ...

Incorporating Bower or NPM Component into an Angular 2/4 cli Project

I am in the process of setting up a basic Angular 4 project with the CLI and I would like to integrate a package from either NPM or Bower into it. The specific package I am interested in is Multi Step Form (https://github.com/troch/angular-multi-step-form) ...

Utilizing URL Router Parameters with Angular 4 for Enhanced Functionality

Is it possible to utilize URLs like prefix/foo-bar-1123 and prefix/foo-bar-1123/bazquux-123 with Angular 4 Router while capturing the numeric IDs? The focus here is extracting the numerical identifiers. I attempted this approach, but it resulted in groupi ...

Setting up types for variables in Angular 2 componentsHere is an

I have a model that consists of multiple properties, and I aim to set all these properties with a default value of either empty or null. Here is an example of my Model: export class MyModel { name: string; jerseyNumber: number; etc... } In m ...

Improving Your Utilization of Angular's @input() Feature

My current dilemma involves a sub-component that requires three variables from the parent component. These three variables all stem from one object, like so: let man = {name:'John',gender:'male',age:42,birthday:'1976-6-12'} ...

Typescript not flagging an error for an object being declared without a type

I am encountering an issue with my tsconfig.json file: { "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "baseUrl": "src", "isolatedModules": true, "jsx": "preserve", "esModuleInterop": true, "forc ...

Double up on your calls to the subscribe function in Angular to ensure successful login

Within my angular 7 application, there is a sign in component that triggers the sign in function within the authentication service. This function initiates an HTTP post request and then subscribes to the response. My goal is to have both the auth service f ...

"Zone has been successfully loaded" - incorporating angular universal ssr

I am currently working on an Angular project and I am looking to implement server-side rendering. To achieve this, I decided to use Angular Universal. The browser module of my project was successfully built, but I encountered the following issue during the ...

What is the method for extracting a value from a variable using a template?

While some may find this basic, I am currently trying to figure it out. I came across another post discussing ngIf else conditionals with templates: How to use *ngIf else?. <div *ngIf="isValid;then content else other_content">here is ignored</di ...

Is there a way to automatically scroll 50 pixels down the page after pressing a button?

Is there a way to make my page scroll down in Angular when a button is clicked? I attempted to use this code, but it didn't have the desired effect. What is the best method for scrolling the page down by 50px? window.scrollBy(0, 50); ...

Utilizing Angular application to access a JSON file located within the assets directory on Microsoft Azure platform

My angular 9 app currently has the ability to access a config.json file located in the assets folder. I have a config service that reads from this file, and everything works fine when running locally. The file path is /dist/assets/config.json. However, wh ...

Angular 7 ESRI loader search widget focus out bug: finding a solution

I am currently working on implementing an ESRI map using esri-loader in my Angular application. Everything seems to be working fine, but I am encountering an error when typing something into the search widget and then focusing out of it. "Uncaught Typ ...

Implementing updates to a particular value in a sub-document in Cosmos DB using Azure Function and TypeScript

I am looking to update a specific value called statutProduit in a sub-document residing within a document collection in Azure Cosmos DB. This will be accomplished using an HttpTrigger Azure Function that requires two parameters: the document ID (id) and th ...

How can we loop through an array of Map<string, string> using ngFor?

There is a property set up as follows: const carac = new Map<string,string>();//Defining the property carac.set("Color", "Blue"); // Setting key value carac.set("age", "99") // Assigning another key value An ar ...

Angular input box with integrated datepicker icons displayed inside

Currently, I have an input field and a datepicker displayed in a row. However, I need to show an icon inside the input box instead. Here is my code: <div class="mb-2" style=" float: left;" class="example-full-width" class= ...

Is there a way to transfer query parameters to my resolver function?

Here is how I initialize the component in my ngOnInit method: ngOnInit() { this.route.queryParams.subscribe( (params) => { console.log(params); } ) } This is my resolver code: class ProductsResolver implements Resolve< ...

Generate a JSON representation of a class within a Spring application

I'm a beginner with Spring and I'm looking to modify the JSON response of my class. public class Mapping { public String name; public Object value; } I want the current format: {"name" : 'value of field name', "value&q ...

What is the method for inserting two dashes within a number?

For the output, I am looking to showcase a number in the following format => 979-9638403-03. At present, the number appears like this => 979963840303. portfolio.ts export class Portfolio { ... DEPO: number; /* DEPO */ const ...

Is there a way to define an object's keys as static types while allowing the values to be dynamically determined?

I am attempting to construct an object where the keys are derived from a string union type and the values are functions. The challenge lies in wanting the function typings to be determined dynamically from each function's implementation instead of bei ...