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);
}